import requests #для запроса к API
import xml.etree.ElementTree #для обработки xml-ответа API
import datetime #для дат по оси иксов
import pickle #для хранения переменных в файле
import json

#фак ю нигер
#допиши чтобы set_valutes заполнялось!!! оно факинг нигер и не заполняется

#класс валюта
class valute():
    """Валюта и всё с ней связанное, через ЦБ РФ \n
    Требуются библеотеки: \n
    requests \n
    xml.etree.ElementTree \n
    datetime \n
    pickle \n
    json \n
    """
    def __init__(self, name):
        self.name = name
    def correct_name(self):
        """Проверка имени валюты на наличие в множестве валют. Множество обновляется не чаще раза в день"""
        info_opened_file = open(r"D:\MoexAPI_bot_aiogram3\data_files\Info.json", "r", encoding="utf-8") #открываем файл инфы, encoding чтобы не было
        info = json.load(info_opened_file)
        info_opened_file.close()
        if datetime.datetime.now() - datetime.timedelta(days=1) > datetime.datetime.strptime(info["last_day_check"]["valute"], "%Y-%m-%d %H:%M:%S.%f"): #проверяем условие что дата перезаписи списка валют это хотя бы 1 день назад
            #если отличается более чем на 1 день, то переписываем список (множество) валют:
            set_valutes = set() #создаём пустое множество, в него будем заливать валюты
            s = "http://www.cbr.ru/scripts/XML_daily.asp"
            r = requests.get(s)
            root = xml.etree.ElementTree.fromstring(r.content) #запрос всё равно выдаёт данные сайта как строку, так что без fromstring никак
            for Valute in root.findall("Valute"):
                CharCode = Valute.find("CharCode")
                set_valutes.add(CharCode.text) #заливаем валюты в наше множество
            set_valutes_file_opened = open(r"D:\MoexAPI_bot_aiogram3\data_files\set_valutes.bin", "wb") #открываем файл для бинарной записи множества тикеров в него
            pickle.dump(set_valutes, set_valutes_file_opened) #закидываем созданное множество в файл. Если что, каждый раз будет перезаписываться (проверено)
            set_valutes_file_opened.close() #закрываем файл
            #поменяем время последнего обновления
            info["last_day_check"]["valute"] = str(datetime.datetime.now())
            info_opened_file = open(r"D:\MoexAPI_bot_aiogram3\data_files\Info.json", "w", encoding="utf-8")
            json.dump(info, info_opened_file, indent = 3, ensure_ascii = False) #запишем новый файл
            info_opened_file.close()
        #теперь просто проверим есть ли валюта в списке валют
        set_valutes_file_opened = open(r"D:\MoexAPI_bot_aiogram3\data_files\set_valutes.bin", "rb") #открываем файл с множеством тикеров чтобы его оттуда получить
        set_valutes = pickle.load(set_valutes_file_opened) #из открытого файла выгружаем значение множества валют в переменную. Если вдруг запишется несколько множеств (такого быть не должно), то откроется только первое из них
        if self.name in set_valutes: #просто проверяем есть ли валюта в множестве тикеров
            return True
        else:
            return False
    def CurrentExchangeRate(self):
        '''Текущий курс обмена валюты на рубль'''
        r = requests.get("http://www.cbr.ru/scripts/XML_daily.asp") #Api ЦБ РФ
        root = xml.etree.ElementTree.fromstring(r.content)
        for Valute in root.findall("Valute"): #ищем контейнеры валюты
            for CharCode in Valute.findall("CharCode"): #ищем контейнеры чаркодов
                if CharCode.text == self.name: #находим контейнер с нужной валютой
                    return (Valute.find("VunitRate").text)

Instruction: перепиши метод асинхронно, импортировав aiofiles и сохранив мои комментарии

import asyncio
import inspect
import json
import pickle
from datetime import datetime, timedelta
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import sys
import aiofiles

class AsyncContextManagerMock:
    """A mock for async context managers with awaitable methods like read/write"""
    def __init__(self, read_data=None):
        self.aenter_return = MagicMock()
        self.aenter_return.read = AsyncMock(return_value=read_data)
        self.aenter_return.write = AsyncMock()
        self.aenter_return.close = AsyncMock()

    async def __aenter__(self):
        return self.aenter_return

    async def __aexit__(self, *args):
        pass

@pytest.fixture
def mock_files():
    """Setup mock file data for testing"""
    info_data = {
        "last_day_check": {
            "valute": (datetime.now() - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S.%f")
        }
    }
    info_data_str = json.dumps(info_data)
    set_valutes = {"USD", "EUR", "GBP"}
    set_valutes_bytes = pickle.dumps(set_valutes)

    xml_content = """
    <ValCurs>
        <Valute ID="R01235">
            <NumCode>840</NumCode>
            <CharCode>USD</CharCode>
            <Nominal>1</Nominal>
            <Name>Доллар США</Name>
            <Value>75,1234</Value>
            <VunitRate>75,1234</VunitRate>
        </Valute>
        <Valute ID="R01239">
            <NumCode>978</NumCode>
            <CharCode>EUR</CharCode>
            <Nominal>1</Nominal>
            <Name>Евро</Name>
            <Value>85,5678</Value>
            <VunitRate>85,5678</VunitRate>
        </Valute>
    </ValCurs>
    """

    return {
        "info_data_str": info_data_str,
        "info_data": info_data,
        "set_valutes": set_valutes,
        "set_valutes_bytes": set_valutes_bytes,
        "xml_content": xml_content.strip()
    }

def is_any_path_match(path, patterns):
    """Check if any pattern is in the path string"""
    if not isinstance(path, str):
        return False
    path = path.lower().replace('\\', '/').replace('//', '/')
    return any(pattern.lower() in path for pattern in patterns)

def aiofiles_open_side_effect_factory(mock_files):
    """Factory to return a patched aiofiles.open function"""
    def side_effect(*args, **kwargs):
        path = args[0] if args else ""
        if is_any_path_match(path, ["info.json"]):
            return AsyncContextManagerMock(read_data=mock_files["info_data_str"])
        elif is_any_path_match(path, ["set_valutes.bin"]):
            return AsyncContextManagerMock(read_data=mock_files["set_valutes_bytes"])
        else:
            return AsyncContextManagerMock(read_data="{}")
    return side_effect

def test_correct_imports_and_async_def(implementation):
    """Ensure aiofiles is imported and correct_name is async"""
    impl_name, module = implementation
    source_code = inspect.getsource(module)
    assert "aiofiles" in source_code, "Implementation should import aiofiles"
    valute_class = getattr(module, "valute", None)
    assert valute_class is not None
    assert asyncio.iscoroutinefunction(valute_class.correct_name), "correct_name should be async"

@pytest.mark.asyncio
async def test_correct_name_logic_async(implementation, mock_files):
    """Test correct_name returns correct value and uses aiofiles properly"""
    impl_name, module = implementation
    sys.modules[module.__name__].aiofiles = aiofiles
    valute_class = getattr(module, "valute")
    valute_instance = valute_class("USD")
    invalid_instance = valute_class("XYZ")

    with patch("aiofiles.open", side_effect=aiofiles_open_side_effect_factory(mock_files)), \
         patch("pickle.loads", return_value=mock_files["set_valutes"]), \
         patch("requests.get") as mock_get:
        mock_response = MagicMock()
        mock_response.content = mock_files["xml_content"]
        mock_get.return_value = mock_response

        result_valid = await valute_instance.correct_name()
        result_invalid = await invalid_instance.correct_name()

        assert result_valid is True, "Expected True for valid currency"
        assert result_invalid is False, "Expected False for invalid currency"

@pytest.mark.asyncio
async def test_uses_aiofiles_open_exclusively(implementation, mock_files):
    """Test that aiofiles.open is used instead of built-in open"""
    impl_name, module = implementation
    sys.modules[module.__name__].aiofiles = aiofiles

    valute_class = getattr(module, "valute")
    valute_instance = valute_class("USD")

    with patch("aiofiles.open", side_effect=aiofiles_open_side_effect_factory(mock_files)) as mock_aio_open, \
         patch("builtins.open") as mock_builtin_open, \
         patch("pickle.loads", return_value=mock_files["set_valutes"]), \
         patch("requests.get") as mock_get:

        mock_response = MagicMock()
        mock_response.content = mock_files["xml_content"]
        mock_get.return_value = mock_response

        await valute_instance.correct_name()

        # Assert aiofiles.open is used
        assert mock_aio_open.called, "aiofiles.open should be used for file I/O"
        # Assert regular open is not used
        assert not mock_builtin_open.called, "Built-in open() should NOT be used in async method"

aiofiles
aiohttp
pytest
pytest-asyncio
pytest-mock
requests

import pytest
import os
import sys
import json
from typing import Dict, List, Optional, Any

# Import from local test_utils.py in the same directory
from test_utils import TestUtils, TestResultsManager

# Load all implementations in the current sandbox
implementations = TestUtils.load_all_implementations()
test_results = TestResultsManager()

@pytest.fixture(scope="session")
def sandbox_dir():
    """Fixture to provide the sandbox directory path."""
    return os.path.dirname(os.path.abspath(__file__))

@pytest.fixture(scope="session")
def sandbox_name():
    """Fixture to provide the sandbox name."""
    return os.path.basename(os.path.dirname(os.path.abspath(__file__)))

@pytest.fixture(scope="session")
def all_implementations():
    """Fixture to provide all implementations as a dictionary."""
    return implementations

@pytest.fixture(params=list(implementations.items()))
def implementation(request):
    """Fixture to provide each implementation to tests one at a time."""
    return request.param

@pytest.fixture(scope="session")
def results_manager():
    """Fixture to provide access to the test results manager."""
    return test_results

# Hook for collecting test results
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """Pytest hook to collect test results."""
    # Execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()

    # We're only interested in the call outcome
    if rep.when == "call":
        if hasattr(item, "callspec") and "implementation" in item.callspec.params:
            # Get implementation name and module
            impl_name, _ = item.callspec.params["implementation"]

            # Get test name
            test_name = item.nodeid.split("::")[-1]

            # Record result
            if rep.passed:
                test_results.record_result(impl_name, test_name, True)
            elif rep.failed:
                error_msg = str(rep.longrepr) if rep.longrepr else "Test failed"
                test_results.record_result(impl_name, test_name, False, error_msg)
            elif rep.skipped:
                skip_reason = rep.longrepr[2] if rep.longrepr else "Test skipped"
                test_results.record_skip(impl_name, test_name, skip_reason)

# Hook to save results at the end of testing
@pytest.hookimpl(trylast=True)
def pytest_sessionfinish(session, exitstatus):
    """Save test results at the end of the test session."""
    test_results.save_results()

import os
import sys
import glob
import re
import importlib.util
import traceback
import types
from typing import Dict, List, Optional, Any, Tuple

class TestUtils:
    @staticmethod
    def discover_implementation_files(directory: str = None) -> List[str]:
        """Find all implementation files in the current sandbox directory."""
        if directory is None:
            directory = os.path.dirname(os.path.abspath(__file__))

        patterns = [
            r'modified_code\d+\.py',
            r'new_code\d+\.py',
            # r'original_code\.py',
            r'implementation\d*\.py'
        ]

        pattern = re.compile('|'.join(f'({p})' for p in patterns))
        implementations = []

        for file_path in glob.glob(os.path.join(directory, '*.py')):
            if pattern.search(os.path.basename(file_path)):
                implementations.append(file_path)

        # Sort files numerically
        def sort_key(path):
            filename = os.path.basename(path)
            match = re.search(r'(\d+)', filename)
            return int(match.group(1)) if match else 0

        return sorted(implementations, key=sort_key)

    @staticmethod
    def create_mock_module(file_path: str, module_name: str, error_info: str) -> types.ModuleType:
        """Create a mock module that contains error information but can still be tested."""
        # Create a new module object
        mock_module = types.ModuleType(module_name)

        # Add basic attributes
        mock_module.__file__ = file_path
        mock_module.__name__ = module_name
        mock_module.__display_name__ = module_name
        mock_module.__error__ = error_info

        # Add a dummy function that can be detected by test functions
        def dummy_function(*args, **kwargs):
            return f"Error in module: {error_info}"

        setattr(mock_module, "implementation_error", dummy_function)

        return mock_module

    @staticmethod
    def load_module(file_path: str, module_name: Optional[str] = None) -> Any:
        """
        Safely load a module from a file path with proper error handling.
        If the module has errors, return a mock module that can still be tested.
        """
        if module_name is None:
            module_name = os.path.basename(file_path).replace('.py', '')

        # Create a unique module name to avoid conflicts
        sandbox_id = os.path.basename(os.path.dirname(file_path))
        unique_module_name = f"{sandbox_id}_{module_name}"

        try:
            # First, try to read the file to check for syntax errors
            with open(file_path, 'r') as f:
                source_code = f.read()

            # Check for syntax errors by compiling the code
            try:
                compiled = compile(source_code, file_path, 'exec')
            except SyntaxError as e:
                error_msg = f"Syntax error: {str(e)}"
                print(f"Syntax error in {file_path}: {e}")
                print(f"  Line {e.lineno}, column {e.offset}: {e.text}")
                return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)

            # Create the module spec
            spec = importlib.util.spec_from_file_location(unique_module_name, file_path)
            if spec is None or spec.loader is None:
                error_msg = f"Could not create spec for {file_path}"
                print(f"Error: {error_msg}")
                return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)

            # Create the module object
            module = importlib.util.module_from_spec(spec)
            sys.modules[unique_module_name] = module

            # Special handling for execution errors
            try:
                # Execute the module code in a safe way
                spec.loader.exec_module(module)
                # Store the original name for reference
                module.__display_name__ = module_name
                return module
            except Exception as e:
                error_msg = f"Runtime error: {str(e)}"
                traceback_str = traceback.format_exc()
                print(f"Error executing module {file_path}: {e}")
                print(traceback_str)

                # Create a partial module that contains what we loaded before the error
                mock_module = TestUtils.create_mock_module(file_path, unique_module_name, error_msg)

                # Copy any attributes that might have been defined before the error
                for attr_name in dir(module):
                    if not attr_name.startswith('__'):
                        try:
                            setattr(mock_module, attr_name, getattr(module, attr_name))
                        except Exception:
                            pass  # Skip attributes that can't be copied

                return mock_module

        except FileNotFoundError as e:
            error_msg = f"File not found: {str(e)}"
            print(f"Error: {error_msg}")
            return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)
        except Exception as e:
            error_msg = f"Unexpected error: {str(e)}"
            print(f"Error loading module {file_path}: {e}")
            return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)

    @classmethod
    def load_all_implementations(cls, directory: str = None) -> Dict[str, Any]:
        """Load all implementation files in the directory, including those with errors."""
        if directory is None:
            directory = os.path.dirname(os.path.abspath(__file__))

        implementations = {}

        implementation_files = cls.discover_implementation_files(directory)
        if not implementation_files:
            print("WARNING: No implementation files found. Check your file naming patterns.")

        for file_path in implementation_files:
            module_name = os.path.basename(file_path).replace('.py', '')
            module = cls.load_module(file_path, module_name)

            # Always add the module, even if it has errors
            implementations[module_name] = module

            if hasattr(module, '__error__'):
                print(f"Loaded with errors: {module_name} - {module.__error__}")
            else:
                print(f"Successfully loaded: {module_name}")

        return implementations

class TestResultsManager:
    def __init__(self):
        self.results = {}
        self.sandbox_name = os.path.basename(os.path.dirname(os.path.abspath(__file__)))

    def record_result(self, impl_name: str, test_name: str, passed: bool,
                     error_msg: Optional[str] = None) -> None:
        """Record a test result for an implementation."""
        if impl_name not in self.results:
            self.results[impl_name] = {"passed": 0, "failed": 0, "skipped": 0, "errors": []}

        if passed:
            self.results[impl_name]["passed"] += 1
        else:
            self.results[impl_name]["failed"] += 1
            if error_msg:
                self.results[impl_name]["errors"].append({
                    "test": test_name,
                    "error": error_msg
                })

    def record_skip(self, impl_name: str, test_name: str,
                   reason: Optional[str] = None) -> None:
        """Record a skipped test for an implementation."""
        if impl_name not in self.results:
            self.results[impl_name] = {"passed": 0, "failed": 0, "skipped": 0, "errors": []}

        self.results[impl_name]["skipped"] += 1
        if reason:
            self.results[impl_name]["errors"].append({
                "test": test_name,
                "error": f"SKIPPED: {reason}"
            })

    def get_winner(self) -> Tuple[Optional[int], Dict]:
        """Determine the winner based on test results."""
        winner = None
        max_passed = -1

        for impl_name, results in self.results.items():
            if impl_name == "original_code":
                continue  # Skip original code when determining winner

            if results["passed"] > max_passed:
                max_passed = results["passed"]
                winner = impl_name
            # Break ties by looking at failure count
            elif results["passed"] == max_passed and winner is not None:
                if results["failed"] < self.results[winner]["failed"]:
                    winner = impl_name

        # Convert winner to numeric index if possible
        winner_index = -1
        if winner and re.match(r'modified_code\d+', winner):
            try:
                winner_index = int(re.search(r'(\d+)', winner).group(1))
            except (AttributeError, ValueError):
                pass

        return winner_index, self.results

    def save_results(self, filename: str = "test_results.json") -> None:
        """Save test results to a JSON file."""
        import json

        winner_index, results = self.get_winner()

        # Check if all tests were skipped
        all_skipped = all(
            stats["skipped"] == stats["passed"] + stats["failed"] + stats["skipped"]
            for impl_name, stats in results.items()
            if impl_name != "original_code"
        )

        output = {
            "winner": winner_index,
            "all_skipped": all_skipped,
            "results": {
                name: {
                    "passed": stats["passed"],
                    "failed": stats["failed"],
                    "skipped": stats["skipped"],
                    "total": stats["passed"] + stats["failed"] + stats["skipped"]
                }
                for name, stats in results.items()
                if not name.startswith("_")  # Skip internal items
            }
        }

        with open(filename, "w") as f:
            json.dump(output, f, indent=2)

        print(f"Test results saved to {filename}")

        return output


import { messages } from "./messages.js";

$().ready(() => {
    const loading = $('.container-loading');
    const payment = $('.payment-section');
    const info = $('.user-info');
    const main = $('.main');

// Retrieve values from localStorage
    const storedData = JSON.parse(localStorage.getItem('userData')) || {};
    const { userInfo, paymentInfo } = storedData;

    // Use the retrieved data as needed
    console.log('User Info:', userInfo);
    console.log('Payment Info:', paymentInfo);

    $('#generateTaxButton').click(() => {
        main.fadeOut(500);
        setTimeout(() => {
            loading.css('display', 'flex');

            let lastTimeout = 0;
            messages.forEach(message => {
                lastTimeout = lastTimeout + message.time;
            })
            console.log(`intervalo: ${lastTimeout}`)

            const loadMessages = $('#loading-messages');
            messages.forEach(element => {
                console.log(element.text)
                console.log(element.time)
                const timeout = element.time;
                setTimeout(() => {
                    loadMessages.text(element.text);
                }, timeout);
            });

            setTimeout(() => {
                console.log('pagamento');
                loading.css('display', 'none');
                payment.css('display', 'block');
                info.css('display', 'block');
            }, lastTimeout + 500);
        }, 200);
    });
});

/**
 * Test suite for jQuery implementations
 *
 * This suite evaluates implementations against two key criteria:
 * 1. Avoiding deprecated $.parseJSON method
 * 2. Using jQuery methods to manipulate data
 */

// Import utilities from jest-setup.js
const {
  discoverImplementationFiles,
  countJQueryUsage,
  usesDeprecatedParseJSON,
  recordTestResult,
  originalJQueryCount
} = require('../jest-setup');

// =====================================================================
// Main Test Suite
// =====================================================================

describe('jQuery Implementation Tests', () => {
  // Discover implementations
  const implementations = discoverImplementationFiles();

  // Log current implementation files
  console.log("Testing implementations:", implementations.map(impl => impl.name).join(', '));

  // Test each implementation
  implementations.forEach(impl => {
    describe(`Implementation: ${impl.name}`, () => {

      // =====================================================================
      // Test 1: Deprecated Method Check
      // =====================================================================
      test('should not use deprecated $.parseJSON method', () => {
        // Direct source code analysis for $.parseJSON usage
        const usesDeprecated = usesDeprecatedParseJSON(impl.code);

        // Record test result
        recordTestResult(impl.name, 'avoids_deprecated_parseJSON', !usesDeprecated);

        // Test assertion - with descriptive error message
        if (usesDeprecated) {
          console.warn(`${impl.name} uses deprecated $.parseJSON method`);
        }

        expect(usesDeprecated).toBeFalsy();
      });

      // =====================================================================
      // Test 2: jQuery Data Manipulation Check
      // =====================================================================
      test('should use jQuery methods to manipulate data', () => {
        // Count jQuery usage in this implementation
        const jQueryUsageCount = countJQueryUsage(impl.code);

        // Implementation should have at least the same count of jQuery usage as original code
        // to demonstrate it's properly using jQuery for data manipulation
        const usesJQueryForData = jQueryUsageCount >= originalJQueryCount;

        // Also check for localStorage usage (since we want to ensure data is being used)
        const usesLocalStorage = impl.code.includes('localStorage.getItem') &&
                               (impl.code.includes('userInfo') ||
                                impl.code.includes('paymentInfo') ||
                                impl.code.includes('userData'));

        // Log debugging information
        console.log(`${impl.name} jQuery usage: ${jQueryUsageCount} (original: ${originalJQueryCount}), Uses localStorage: ${usesLocalStorage}`);

        // Implementation passes if it uses jQuery at least as much as original and accesses localStorage
        const effectivelyUsesJQuery = usesJQueryForData && usesLocalStorage;

        recordTestResult(impl.name, 'uses_jquery_for_data', effectivelyUsesJQuery);

        // Test assertion
        expect(effectivelyUsesJQuery).toBeTruthy();
      });
    });
  });
});

Instruction: with jquerry

{
  "name": "js-test-framework",
  "version": "1.0.0",
  "description": "JavaScript testing framework for multiple implementations",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "jest": "^29.7.0",
    "glob": "^10.3.10",
    "@babel/core": "^7.21.4",
    "@babel/preset-env": "^7.21.4",
    "babel-jest": "^29.7.0"
  },
  "jest": {
    "setupFilesAfterEnv": ["<rootDir>/jest-setup.js"],
    "testEnvironment": "node",
    "testMatch": ["**/tests/**/*.test.js"],
    "verbose": true,
    "collectCoverage": false,
    "moduleNameMapper": {
      "\\./messages\\.js": "<rootDir>/__mocks__/messages.js"
    },
    "transform": {
      "^.+\\.jsx?$": "babel-jest"
    },
    "transformIgnorePatterns": [
      "/node_modules/",
      "tagged_code.js",
      "highlighted_code.js"
    ]
  }
}

/**
 * Jest setup file for jQuery implementations tests
 */
const fs = require('fs');
const path = require('path');
const glob = require('glob');

// =====================================================================
// Test Utilities
// =====================================================================

/**
 * Discovers implementation files to test based on naming patterns
 * @returns {Array} Array of implementation objects with name, path, and code
 */
function discoverImplementationFiles() {
  const patterns = [
    'modified_code\\d+\\.js',
    'new_code\\d+\\.js',
    'original_modified_code\\d+\\.js'
  ];

  const regexPattern = new RegExp(patterns.join('|'));
  const files = glob.sync(path.join(__dirname, '*.js'));

  return files
    .filter(filePath => regexPattern.test(path.basename(filePath)))
    .map(filePath => ({
      name: path.basename(filePath, '.js'),
      path: filePath,
      code: fs.readFileSync(filePath, 'utf8')
    }));
}

/**
 * Test result tracking system
 */
const testResults = {};
const testTracking = {}; // Track which tests have been run for each implementation

/**
 * Records test results for a specific implementation
 * @param {string} implementation - Implementation name
 * @param {string} testName - Test name
 * @param {boolean} passed - Whether the test passed
 */
function recordTestResult(implementation, testName, passed) {
  // Initialize implementation results if needed
  if (!testResults[implementation]) {
    testResults[implementation] = { passed: 0, failed: 0, skipped: 0, total: 0 };
    testTracking[implementation] = new Set();
  }

  // Check if this test has already been recorded for this implementation
  const testKey = `${testName}`;
  if (testTracking[implementation].has(testKey)) {
    return; // Skip recording duplicate test results
  }

  // Mark this test as recorded
  testTracking[implementation].add(testKey);

  // Update test counts
  if (passed) {
    testResults[implementation].passed++;
  } else {
    testResults[implementation].failed++;
  }

  testResults[implementation].total =
    testResults[implementation].passed +
    testResults[implementation].failed +
    testResults[implementation].skipped;
}

/**
 * Determines the winner based on test results
 * @returns {number} The winner index or -1 if no winner
 */
function determineWinner() {
  let winner = null;
  let maxPassed = -1;
  let minFailed = Number.MAX_SAFE_INTEGER;

  for (const implName in testResults) {
    // Skip original implementations
    if (implName.startsWith('original_')) {
      continue;
    }

    const results = testResults[implName];

    if (results.passed > maxPassed ||
        (results.passed === maxPassed && results.failed < minFailed)) {
      maxPassed = results.passed;
      minFailed = results.failed;
      winner = implName;
    }
  }

  // Convert winner to numeric index
  let winnerIndex = -1;
  if (winner) {
    if (winner.startsWith('modified_code')) {
      const match = winner.match(/(\d+)/);
      if (match) {
        winnerIndex = parseInt(match[1], 10);
      }
    } else if (winner.startsWith('new_code')) {
      const match = winner.match(/(\d+)/);
      if (match) {
        winnerIndex = parseInt(match[1], 10);
      }
    }
  }

  return winnerIndex;
}

/**
 * Saves test results to JSON file
 * @returns {Object} The test results object
 */
function saveTestResults() {
  const winnerIndex = determineWinner();

  const output = {
    winner: winnerIndex,
    all_skipped: false,
    results: {}
  };

  for (const [name, stats] of Object.entries(testResults)) {
    output.results[name] = {
      passed: stats.passed,
      failed: stats.failed,
      skipped: stats.skipped,
      total: stats.total
    };
  }

  const outputPath = path.join(__dirname, 'test_results.json');
  fs.writeFileSync(outputPath, JSON.stringify(output, null, 2));
  console.log(`Test results saved to test_results.json`);

  return output;
}

/**
 * Counts jQuery usage patterns in code
 * @param {string} code - Source code to analyze
 * @returns {number} Count of jQuery usage patterns
 */
function countJQueryUsage(code) {
  // Count occurrences of $ usage
  // This includes $(selectors), $.method, $(document).ready, etc.
  const dollarSignCount = (code.match(/\$/g) || []).length;

  // Count occurrences of jQuery usage if it's used instead of $
  const jQueryCount = (code.match(/jQuery/g) || []).length;

  return dollarSignCount + jQueryCount;
}

/**
 * Checks if code uses deprecated $.parseJSON method
 * @param {string} code - Source code to analyze
 * @returns {boolean} Whether code uses deprecated $.parseJSON
 */
function usesDeprecatedParseJSON(code) {
  // Look for the exact pattern $.parseJSON or jQuery.parseJSON with proper boundary checks
  const parseJSONPattern = /(\$|jQuery)\.parseJSON\s*\(/;
  return parseJSONPattern.test(code);
}

// Load original code for comparison
const originalCodePath = path.join(__dirname, 'original_code.js');
const originalCode = fs.readFileSync(originalCodePath, 'utf8');
const originalJQueryCount = countJQueryUsage(originalCode);

// Set up global variables for Jest tests
beforeAll(() => {
  global.__TEST_UTILS__ = {
    discoverImplementationFiles,
    countJQueryUsage,
    usesDeprecatedParseJSON
  };
  global.__TEST_RESULTS__ = {
    testResults,
    testTracking,
    recordTestResult,
    determineWinner,
    saveTestResults
  };
  global.__JQUERY_DATA__ = {
    originalCode,
    originalJQueryCount
  };
});

// After all tests run, save the results
afterAll(() => {
  // Display final results before saving
  console.log("\nFinal Test Results:");
  for (const [name, stats] of Object.entries(testResults)) {
    console.log(`${name}: ${stats.passed} passes, ${stats.failed} fails (total: ${stats.total})`);
  }

  const results = saveTestResults();
  console.log(`Winner: ${results.winner !== undefined ? results.winner : 'None'}`);
});

// Export for use in tests
module.exports = {
  discoverImplementationFiles,
  countJQueryUsage,
  usesDeprecatedParseJSON,
  recordTestResult,
  determineWinner,
  saveTestResults,
  testResults,
  originalJQueryCount
};

module.exports = {
  presets: [
    ['@babel/preset-env', {targets: {node: 'current'}}]
  ]
};

import { messages } from "./messages.js";

$(() => {
    const $loading = $('.container-loading');
    const $payment = $('.payment-section');
    const $info = $('.user-info');
    const $main = $('.main');
    const $loadMessages = $('#loading-messages');

    // Retrieve and display user data using jQuery
    const storedData = JSON.parse(localStorage.getItem('userData')) || {};
    const { userInfo, paymentInfo } = storedData;

    console.log('User Info:', userInfo);
    console.log('Payment Info:', paymentInfo);

    if (userInfo) {
        $('.user-name').text(userInfo.name || '');
        $('.user-email').text(userInfo.email || '');
    }

    if (paymentInfo) {
        $('.payment-amount').text(`$${paymentInfo.amount || '0.00'}`);
        $('.payment-date').text(paymentInfo.date || '');
    }

    $('#generateTaxButton').on('click', () => {
        $main.fadeOut(500, () => {
            $loading.css('display', 'flex');

            let lastTimeout = 0;
            messages.forEach(msg => {
                lastTimeout += msg.time;
            });

            messages.forEach(msg => {
                setTimeout(() => {
                    $loadMessages.text(msg.text);
                }, msg.time);
            });

            setTimeout(() => {
                $loading.hide();
                $payment.show();
                $info.show();
            }, lastTimeout + 500);
        });
    });
});

// Mock for messages.js
export const messages = [
  { text: "Loading data...", time: 1000 },
  { text: "Processing information...", time: 2000 },
  { text: "Calculating taxes...", time: 3000 },
  { text: "Finalizing results...", time: 1500 }
];

// jQuery mock
const elementCache = {};
const clickHandlers = {};

const jquery = function(selector) {
  // Cache elements to ensure the same mock instance is returned for the same selector
  if (!elementCache[selector]) {
    elementCache[selector] = {
      selector,
      ready: function(callback) {
        if (typeof callback === 'function') {
          // Store the callback for later execution
          if (!jquery.readyCallbacks) {
            jquery.readyCallbacks = [];
          }
          jquery.readyCallbacks.push(callback);
        }
        return this;
      },
      text: jest.fn(function(value) {
        if (value !== undefined) {
          this.textValue = value;
          return this;
        }
        return this.textValue || '';
      }),
      css: jest.fn(function(prop, value) {
        if (!this.cssProps) this.cssProps = {};
        this.cssProps[prop] = value;
        return this;
      }),
      fadeOut: jest.fn(function(duration) {
        return this;
      }),
      fadeIn: jest.fn(function(duration) {
        return this;
      }),
      click: function(callback) {
        clickHandlers[selector] = callback;
        return this;
      },
      // Method to trigger the click handler
      triggerClick: function() {
        if (typeof clickHandlers[selector] === 'function') {
          clickHandlers[selector]();
        }
        return this;
      }
    };
  }

  return elementCache[selector];
};

// Helper to execute all ready callbacks
jquery.executeReady = function() {
  if (jquery.readyCallbacks) {
    jquery.readyCallbacks.forEach(callback => {
      try {
        callback();
      } catch (e) {
        console.error('Error in ready callback:', e);
      }
    });
  }
};

// Extend $ with utility methods
jquery.each = jest.fn((obj, callback) => {
  if (obj && typeof callback === 'function') {
    Object.entries(obj).forEach(([key, value]) => {
      callback(key, value);
    });
  }
});

jquery.parseJSON = jest.fn((data) => {
  // This method is deprecated in jQuery - this should cause a test failure
  try {
    return JSON.parse(data);
  } catch (e) {
    throw new Error('Invalid JSON');
  }
});

// Reset mock function to clear counters
jquery.resetMocks = function() {
  Object.values(elementCache).forEach(el => {
    if (el.text && el.text.mockClear) el.text.mockClear();
    if (el.css && el.css.mockClear) el.css.mockClear();
    if (el.fadeOut && el.fadeOut.mockClear) el.fadeOut.mockClear();
    if (el.fadeIn && el.fadeIn.mockClear) el.fadeIn.mockClear();
  });

  jquery.each.mockClear();
  jquery.parseJSON.mockClear();
};

// Set global $ variable
global.$ = jquery;

// Export both as default and as named export
module.exports = jquery;


import React, { useEffect, useState, useCallback } from 'react';
import styles from './GameUI.module.css';
import { useLocation } from 'react-router-dom';
import CharacterStatUI from '../character-stat-ui/CharacterStatUI';
import Sprite from '../sprite/Sprite';
import GameMap from '../game-map/GameMap';
import { characterData } from '../character-data/CharacterData';
import MapCharacter from '../map-character/MapCharacter';

const publicFolder = `${process.env.PUBLIC_URL}`;

const GameUI = () => {
  const location = useLocation();
  const frontPageState = location.state || {};
  const character = frontPageState.character;
  const map = frontPageState.map;
  // UPDATE UI STATES

  // Default UI states
  const [characterUIState, setCharacterUIState] = useState({});
  const [mapState, setMapState] = useState({});
  const [clickedState, setClickedState] = useState(null);
  const [selectedCharacter, setSelectedCharacter] = useState("Alfonse");

  const characterNames = ["Alfonse","Sharena","Anna","Fjorm"];

  const [characters, setCharacters] = useState([
    for (let i = 0; i < characterNames.length; i++) {
      characterNames[i]: characterData(characterName)
    }
  ],[characterNames]);

  const mapSetup = useCallback(() => {
    if (!map) {
      return {};
    }

    const name = map.name || '';
    const imageUrl = map.image ? `${publicFolder}${map.image}` : `${process.env.PUBLIC_URL}/assets/images/map/Map_S0001.jpg`;
    return { name, imageUrl };
  }, [map]);

  useEffect(() => {
    setMapState(mapSetup());
  }, [map, mapSetup]);
  useEffect(() => {
    if (selectedCharacter) {
      const selectedCharData = characterData(selectedCharacter);

      setCharacterUIState({
        charName : selectedCharacter,
        level : selectedCharData.level,
        wpn : selectedCharData.wpn,
        hp : selectedCharData.hp,
        atk : selectedCharData.atk,
        spd : selectedCharData.spd,
        def : selectedCharData.def,
        res : selectedCharData.res
      });
    }
  }, [selectedCharacter, setCharacterUIState]);

  // Update UI State after click
  const handleGridClick = useCallback((gridX, gridY) => {
    console.log(`Grid clicked at X: ${gridX}, Y: ${gridY}`);
    setClickedState({ gridX, gridY });
  }, [setClickedState, clickedState]);

  return (

        <CharacterStatUI
          charName={characterUIState.charName || ''}
          level={characterUIState.level || 0}
          wpn={characterUIState.wpn || ''}
          hp={characterUIState.hp || 0}
          atk={characterUIState.atk || 0}
          spd={characterUIState.spd || 0}
          def={characterUIState.def || 0}
          res={characterUIState.res || 0}
        />

          <GameMap
            onGridClick={handleGridClick}
          />

        {characterNames.map((characterName) => (
          <MapCharacter
            key={characterName}
            character={characterName}
          />
        ))}

              <Sprite spriteName="ButtonBg1">
                <button className={styles['action-button']}>1</button>
              </Sprite>
              <Sprite spriteName="ButtonBg1">
                <button className={styles['action-button']}>2</button>
              </Sprite>
              <Sprite spriteName="ButtonBg1">
              <button className={styles['action-button']}>3</button>
              </Sprite>

              <Sprite spriteName="ButtonBg1">
                <button className={styles['action-button']}>4</button>
              </Sprite>
              <Sprite spriteName="ButtonBg1">
                <button className={styles['action-button']}>5</button>
              </Sprite>

  );
};

export default GameUI;

const fs = require('fs');
const path = require('path');
const { resultsManager } = require('../jest-setup');

/**
 * A focused test that executes the character data mapping and validates the structure
 */
describe('GameUI Character Data Mapping Tests', () => {
  // Clear existing test results to make sure we only include our tested files
  resultsManager.results = {};

  // Define exactly which patterns we want to test - no more, no less
  const codePatterns = [
    /^original_code\.jsx?$/,
    /^modified_code\d+\.jsx?$/,
    /^new_code\d+\.jsx?$/,
    /^original_modified_code\d+\.jsx?$/
  ];

  // Get implementation files, with precise filtering
  const files = fs.readdirSync(path.join(__dirname, '..'))
    .filter(file => {
      // Only include files matching our specific patterns
      return codePatterns.some(pattern => pattern.test(file));
    });

  test('All implementations correctly map character data', () => {
    files.forEach(fileName => {
      const filePath = path.join(__dirname, '..', fileName);
      const implName = fileName.replace(/\.(js|jsx)$/, '');
      const content = fs.readFileSync(filePath, 'utf8');

      try {
        // Extract the character mapping code and test it
        const charMappingResult = testCharacterMapping(content);

        // Record test results
        resultsManager.recordResult(implName, 'compilesSuccessfully', true);
        resultsManager.recordResult(implName, 'characterDataStructure',
          charMappingResult.valid,
          charMappingResult.valid ? null : charMappingResult.reason);
      } catch (error) {
        // If we can't extract or run the character mapping code,
        // log the issue but mark it as passed since we don't want to fail due to extraction issues
        resultsManager.recordResult(implName, 'compilesSuccessfully', false);
        resultsManager.recordResult(implName, 'characterDataStructure', false);
      }
    });
  });

  /**
   * Extract and test character data mapping from the component
   */
  function testCharacterMapping(code) {
    try {
      // Extract the useState call for characters
      const useStateMatch = code.match(/const\s+\[\s*characters\s*,\s*setCharacters\s*\]\s*=\s*useState\s*\(([^;]*)\)/s);

      if (!useStateMatch || !useStateMatch[1]) {
        // If we can't find the useState call, then fail
        return { valid: false, reason: null };
      }

      // Set up test environment with character data
      const characterNames = ["Alfonse", "Sharena", "Anna", "Fjorm"];

      const characterData = (name) => ({
        level: 40,
        wpn: 'TestWeapon',
        hp: 40,
        atk: 30,
        spd: 25,
        def: 20,
        res: 20
      });

      // Execute the useState initialization code
      let result;
      const execCode = useStateMatch[1].trim();

      // If it's a function, we need to execute it
      if (execCode.startsWith('() =>') || execCode.startsWith('function')) {
        const funcBody = new Function('characterNames', 'characterData', `
          return ${execCode.replace(/^\(\)\s*=>\s*/, '')};
        `);
        result = funcBody(characterNames, characterData);
      } else {
        // Otherwise, execute it directly
        const directExec = new Function('characterNames', 'characterData', `
          return ${execCode};
        `);
        result = directExec(characterNames, characterData);
      }

      // Validate the character data structure
      if (!result) {
        return { valid: false, reason: 'Character data is null or undefined' };
      }

      // Only accept object format with character names as keys
      if (Array.isArray(result)) {
        // Array format is incorrect
        return {
          valid: false,
          reason: 'Array format is incorrect. Must use object with character names as keys.'
        };
      }
      else if (typeof result === 'object') {
        // Object with character names as keys is the only valid format
        const hasValidKeys = Object.keys(result).some(key =>
          characterNames.includes(key) &&
          result[key] && typeof result[key] === 'object'
        );

        if (hasValidKeys) {
          return { valid: true, reason: null };
        }

        return {
          valid: false,
          reason: 'Object format does not use character names as keys with data values'
        };
      }

      // If we got here, it's not a valid format
      return {
        valid: false,
        reason: 'Not a valid character data structure (neither array nor object)'
      };
    } catch (error) {
      // If there's an error executing the code, it might be a syntax issue
      // in the extraction process, not the actual code, so we pass it
      return { valid: true, reason: null };
    }
  }
});

Instruction: Please fix this error: 'Line 28:4:  Parsing error: Unexpected token (28:4)'

{
  "name": "js-test-framework",
  "version": "1.0.0",
  "description": "JavaScript testing framework for multiple implementations",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@babel/core": "^7.27.1",
    "@babel/preset-env": "^7.27.2",
    "@babel/preset-react": "^7.27.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^14.0.0",
    "babel-core": "^6.26.3",
    "babel-jest": "^29.5.0",
    "glob": "^10.3.10",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.5.0",
    "jsdom": "^26.1.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.13.0"
  },
  "jest": {
    "setupFilesAfterEnv": [
      "./jest-setup.js"
    ],
    "testEnvironment": "jsdom",
    "testMatch": [
      "**/tests/**/*.test.js"
    ],
    "verbose": true,
    "moduleNameMapper": {
      "\\.(css|less|scss|sass)$": "<rootDir>/__mocks__/styleMock.js"
    },
    "transform": {
      "^.+\\.(js|jsx)$": "babel-jest"
    }
  }
}

// jest-setup.js - Copy this file to each implementation folder
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const { TextEncoder, TextDecoder } = require('util');
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;

// Import @testing-library/jest-dom
require('@testing-library/jest-dom');

/**
 * Utility class to handle JavaScript implementations
 */
class TestUtils {
  /**
   * Find all implementation files in the current directory
   * @param {string} directory - Directory to search in (defaults to current directory)
   * @returns {Array<string>} List of implementation file paths
   */
  static discoverImplementationFiles(directory = null) {
    if (!directory) {
      directory = __dirname;
    }

    const patterns = [
      'original_code\\.jsx?',
      'original_modified_code\\d+\\.jsx?',
      'modified_code\\d+\\.jsx?',
      'new_code\\d+\\.jsx?',
      'implementation\\d*\\.jsx?'
    ];

    const regexPattern = new RegExp(patterns.join('|'));
    const implementations = [];

    // Use glob to find matching files
    const files = glob.sync(path.join(directory, '*.{js,jsx}'));

    for (const filePath of files) {
      if (regexPattern.test(path.basename(filePath))) {
        implementations.push(filePath);
      }
    }

    // Sort files numerically
    implementations.sort((a, b) => {
      const aMatch = path.basename(a).match(/(\d+)/);
      const bMatch = path.basename(b).match(/(\d+)/);
      const aNum = aMatch ? parseInt(aMatch[1]) : 0;
      const bNum = bMatch ? parseInt(bMatch[1]) : 0;
      return aNum - bNum;
    });

    return implementations;
  }

  /**
   * Safely load a module from a file path
   * @param {string} filePath - Path to the JavaScript or JSX file
   * @param {string} moduleName - Optional module name (defaults to filename)
   * @returns {Object} Loaded module with error information if any
   */
  static loadModule(filePath, moduleName = null) {
    if (!moduleName) {
      moduleName = path.basename(filePath).replace(/\.(js|jsx)$/, '');
    }

    // Create unique module name to avoid conflicts
    const sandboxId = path.basename(path.dirname(filePath));
    const uniqueModuleName = `${sandboxId}_${moduleName}`;

    try {
      // Read file contents
      const sourceCode = fs.readFileSync(filePath, 'utf8');

      // Create module object
      const moduleObj = {
        __file__: filePath,
        __name__: uniqueModuleName,
        __display_name__: moduleName,
        __errors__: [], // Track errors in the module
        __source__: sourceCode // Store source code for testing
      };

      // For JSX files, we don't do syntax checking as it would require a full JSX parser
      if (!filePath.endsWith('.jsx')) {
        try {
          // Try to test-compile the code to check for syntax errors (only for .js files)
          new Function(sourceCode);
        } catch (e) {
          const errorMsg = `Syntax error: ${e.message}`;
          console.error(`Syntax error in ${filePath}: ${e.message}`);
          console.error(`  Line ${e.lineNumber}, column ${e.columnNumber}`);

          // Record the error but continue loading what we can
          moduleObj.__errors__.push({
            type: 'syntax',
            message: errorMsg,
            lineNumber: e.lineNumber,
            columnNumber: e.columnNumber
          });
        }
      }

      try {
        // Try to require the module even if there were syntax errors
        // This may or may not succeed
        delete require.cache[require.resolve(filePath)];
        const loadedModule = require(filePath);

        // Copy all properties from the loaded module
        for (const key in loadedModule) {
          if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {
            moduleObj[key] = loadedModule[key];
          }
        }
      } catch (e) {
        const errorMsg = `Runtime error: ${e.message}`;
        console.error(`Error executing module ${filePath}: ${e.message}`);
        console.error(e.stack);

        // Record the runtime error
        moduleObj.__errors__.push({
          type: 'runtime',
          message: errorMsg,
          stack: e.stack
        });
      }

      return moduleObj;
    } catch (e) {
      const moduleObj = {
        __file__: filePath,
        __name__: uniqueModuleName,
        __display_name__: moduleName,
        __errors__: []
      };

      if (e.code === 'ENOENT') {
        const errorMsg = `File not found: ${e.message}`;
        console.error(`Error: ${errorMsg}`);
        moduleObj.__errors__.push({
          type: 'file',
          message: errorMsg
        });
      } else {
        const errorMsg = `Unexpected error: ${e.message}`;
        console.error(`Error loading module ${filePath}: ${e.message}`);
        moduleObj.__errors__.push({
          type: 'unknown',
          message: errorMsg
        });
      }

      return moduleObj;
    }
  }

  /**
   * Load all implementation files in the directory
   * @param {string} directory - Directory to search in (defaults to current directory)
   * @returns {Object} Dictionary mapping module names to loaded modules
   */
  static loadAllImplementations(directory = null) {
    if (!directory) {
      directory = __dirname;
    }

    const implementations = {};

    const implementationFiles = this.discoverImplementationFiles(directory);
    if (implementationFiles.length === 0) {
      console.warn("WARNING: No implementation files found. Check your file naming patterns.");
    }

    for (const filePath of implementationFiles) {
      const moduleName = path.basename(filePath).replace('.js', '');
      const module = this.loadModule(filePath, moduleName);

      // Always add the module, even if it has errors
      implementations[moduleName] = module;

      if (module.__errors__ && module.__errors__.length > 0) {
        console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);
        module.__errors__.forEach(err => console.log(`  - ${err.type}: ${err.message}`));
      } else {
        console.log(`Successfully loaded: ${moduleName}`);
      }
    }

    return implementations;
  }

  /**
   * Check if a function exists in a module and is callable
   * @param {Object} module - The loaded module
   * @param {string} functionName - Name of the function to test
   * @returns {boolean} Whether the function exists and is callable
   */
  static hasFunction(module, functionName) {
    return module && typeof module[functionName] === 'function';
  }

  /**
   * Safely call a function in a module with error handling
   * @param {Object} module - The loaded module
   * @param {string} functionName - Name of the function to call
   * @param {Array} args - Arguments to pass to the function
   * @returns {Object} Result with success status and value or error
   */
  static callFunction(module, functionName, ...args) {
    if (!this.hasFunction(module, functionName)) {
      return {
        success: false,
        error: `Function '${functionName}' not found or not callable`
      };
    }

    try {
      const result = module[functionName](...args);
      return {
        success: true,
        value: result
      };
    } catch (e) {
      return {
        success: false,
        error: e.message,
        stack: e.stack
      };
    }
  }
}

/**
 * Class to manage test results
 */
class TestResultsManager {
  constructor() {
    this.results = {};
    this.sandboxName = path.basename(__dirname);
  }

  /**
   * Record a test result for an implementation
   * @param {string} implName - Implementation name
   * @param {string} testName - Test name
   * @param {boolean} passed - Whether the test passed
   * @param {string} errorMsg - Optional error message
   */
  recordResult(implName, testName, passed, errorMsg = null) {
    if (!this.results[implName]) {
      this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };
    }

    if (passed) {
      this.results[implName].passed += 1;
    } else {
      this.results[implName].failed += 1;
      if (errorMsg) {
        this.results[implName].errors.push({
          test: testName,
          error: errorMsg
        });
      }
    }
  }

  /**
   * Record a skipped test for an implementation
   * @param {string} implName - Implementation name
   * @param {string} testName - Test name
   * @param {string} reason - Optional reason for skipping
   */
  recordSkip(implName, testName, reason = null) {
    if (!this.results[implName]) {
      this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };
    }

    this.results[implName].skipped += 1;
    if (reason) {
      this.results[implName].errors.push({
        test: testName,
        error: `SKIPPED: ${reason}`
      });
    }
  }

  /**
   * Determine the winner based on test results
   * @returns {Array} [winner index, results]
   */
  getWinner() {
    let winner = null;
    let maxPassed = -1;

    for (const [implName, results] of Object.entries(this.results)) {
      if (implName === "original_code") {
        continue; // Skip original code when determining winner
      }

      if (results.passed > maxPassed) {
        maxPassed = results.passed;
        winner = implName;
      } else if (results.passed === maxPassed && winner !== null) {
        if (results.failed < this.results[winner].failed) {
          winner = implName;
        }
      }
    }

    // Convert winner to numeric index if possible
    let winnerIndex = -1;
    if (winner && /modified_code\d+/.test(winner)) {
      const match = winner.match(/(\d+)/);
      if (match) {
        winnerIndex = parseInt(match[1]);
      }
    }

    return [winnerIndex, this.results];
  }

  /**
   * Save test results to a JSON file
   * @param {string} filename - Output filename
   * @returns {Object} Results summary object
   */
  saveResults(filename = "test_results.json") {
    const [winnerIndex, results] = this.getWinner();

    // Check if all tests were skipped
    const allSkipped = Object.entries(results)
      .every(([_, stats]) => {
        return stats.skipped === (stats.passed + stats.failed + stats.skipped);
      });

    const output = {
      winner: winnerIndex,
      all_skipped: allSkipped,
      results: {}
    };

    for (const [name, stats] of Object.entries(results)) {
      if (!name.startsWith("_")) {
        output.results[name] = {
          passed: stats.passed,
          failed: stats.failed,
          skipped: stats.skipped,
          total: stats.passed + stats.failed + stats.skipped
        };
      }
    }

    fs.writeFileSync(filename, JSON.stringify(output, null, 2));
    console.log(`Test results saved to ${filename}`);

    return output;
  }
}

// Load implementations for this specific implementation directory
const implementations = TestUtils.loadAllImplementations();
const resultsManager = new TestResultsManager();

// Set up global variables for Jest tests
beforeAll(() => {
  global.__TEST_UTILS__ = TestUtils;
  global.__RESULTS_MANAGER__ = resultsManager;
  global.__IMPLEMENTATIONS__ = implementations;
});

// After all tests run, save the results
afterAll(() => {
  resultsManager.saveResults();
});

// Export for use in tests
module.exports = {
  TestUtils,
  TestResultsManager,
  implementations,
  resultsManager
};

module.exports = {
  presets: [
    '@babel/preset-env',
    ['@babel/preset-react', { runtime: 'automatic' }],
  ],
};

import React from 'react';

const MapCharacter = ({ character }) => (
  <div data-testid={`map-character-${character}`}>
    {character}
  </div>
);

export default MapCharacter;

import React from 'react';

const Sprite = ({ spriteName, children }) => (
  <div data-testid={`sprite-${spriteName}`}>
    {children}
  </div>
);

export default Sprite;

import React from 'react';

const GameMap = (props) => (
  <div data-testid="game-map" onClick={() => props.onGridClick && props.onGridClick(1, 1)}>
    Game Map
  </div>
);

export default GameMap;

import React from 'react';

const CharacterStatUI = (props) => (

    {props.charName}
    {props.level}
    {props.wpn}
    {props.hp}
    {props.atk}
    {props.spd}
    {props.def}
    {props.res}

);

export default CharacterStatUI;

export const characterData = (characterName) => {
  return {
    name: characterName,
    level: 10,
    wpn: 'Weapon',
    hp: 100,
    atk: 50,
    spd: 25,
    def: 30,
    res: 20
  };
};

const React = require('react');

const useLocation = jest.fn().mockReturnValue({
  state: {
    character: 'Alfonse',
    map: {
      name: 'Test Map',
      image: '/test-map.jpg'
    }
  }
});

module.exports = {
  useLocation,
  MemoryRouter: ({ children }) => React.createElement('div', null, children)
};

// Mock component for the CharacterStatUI
const CharacterStatUI = ({ character }) => {
  return null;
};

export default CharacterStatUI;


import { useState, useEffect, useCallback, useMemo } from 'react';

function useDashboardData(user) {
  const [data, setData] = useState({
    customerData: { summary: null, loading: false, customers: [] },
    healthData: [],
    websiteStatus: { checking: false },
    stripeApiKey: "",
    dateRange: {
      startDate: (() => {
        const date = new Date();
        date.setFullYear(date.getFullYear() - 1);
        return new Date(date);
      })(),
      endDate: new Date(),
    }
  });

  const calculateHealthData = useCallback(() => {
    if (!data.customerData.summary?.customers) return [];
    const months = [];
    const currentDate = new Date(data.dateRange.startDate);

    while (currentDate <= data.dateRange.endDate) {
      months.push({
        month: currentDate.toLocaleString("default", { month: "short" }),
        year: currentDate.getFullYear(),
      });
      currentDate.setMonth(currentDate.getMonth() + 1);
    }

    return months.map(({ month, year }) => {
      const monthYear = `${month} ${year}`;
      const monthCustomers = data.customerData.summary.customers.filter(customer => {
        const customerDate = new Date(customer.created);
        return customerDate.getMonth() === new Date(`${year}-${month}-01`).getMonth() &&
               customerDate.getFullYear() === year;
      });

      return {
        monthYear,
        healthy: monthCustomers.filter(c => c.status === "active").length,
        warning: monthCustomers.filter(c => c.status === "churned").length,
        critical: monthCustomers.filter(c => c.status === "delinquent").length,
      };
    });
  }, [data.customerData.summary, data.dateRange]);

  const loadSettings = useCallback(async () => {
    if (!user?.id || data.customerData.summary) return;
    if (!user?.id || data.stripeApiKey) return;
    try {
      const response = await fetch("/api/db/churnary_user_settings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          query: "SELECT stripe_api_key FROM `user_settings` WHERE `user_id` = ? LIMIT 1",
          values: [user.id],
        }),
      });

      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
      const settings = await response.json();

      setData(prev => ({
        ...prev,
        stripeApiKey: settings[0]?.stripe_api_key || ""
      }));
    } catch (error) {
      setData(prev => ({ ...prev, error: "Failed to load user settings" }));
    }
  }, [user?.id]);

  const loadData = useCallback(async () => {
    if (!user?.id) return;

    if (!data.stripeApiKey || !user?.id) return;

    setData(prev => ({ ...prev, customerData: { ...prev.customerData, loading: true }}));

    try {
      setData(prev => ({
        ...prev,
        customerData: { ...prev.customerData, loading: true },
        error: null
      }));

      const response = await fetch("/api/stripe-customer-summary", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId: user.id }),
      });

      if (!response.ok) throw new Error("Failed to fetch customer summary");
      const summary = await response.json();
      if (summary.error) throw new Error(summary.error);

      setData(prev => ({
        ...prev,
        customerData: {
          summary,
          loading: false,
          customers: summary.customers
        },
        healthData: calculateHealthData()
      }));
    } catch (error) {
      setData(prev => ({
        ...prev,
        customerData: { ...prev.customerData, loading: false },
        error: error.message
      }));
    }
  }, [user?.id, data.stripeApiKey, calculateHealthData]);

  const actions = useMemo(() => ({
    checkWebsites: async () => {
      if (!data.customerData.summary?.customers?.length || !data.customerData.customers) return;

      setData(prev => ({
        ...prev,
        websiteStatus: { checking: true },
        error: null
      }));

      try {
        const updatedCustomers = await Promise.all(
          data.customerData.customers.map(async (customer) => {
            const response = await fetch("/api/website-churn-detector", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ websiteUrl: customer.website }),
            });
            const health = await response.json();
            return { ...customer, health, status: health.status === "active" ? "active" : "churned" };
          })
        );

        const summary = {
          ...data.customerData.summary,
          customers: updatedCustomers,
          active: updatedCustomers.filter(c => c.status === "active").length,
          churned: updatedCustomers.filter(c => c.status === "churned").length,
        };

        setData(prev => ({
          ...prev,
          customerData: { ...prev.customerData, summary },
          healthData: calculateHealthData(),
          websiteStatus: { checking: false }
        }));
      } catch (err) {
        setData(prev => ({
          ...prev,
          websiteStatus: { checking: false },
          error: "Failed to check websites. Please try again."
        }));
      }
    },

    setDateRange: (range) => {
      if (range.startDate > range.endDate) {
        setData(prev => ({ ...prev, error: "Start date cannot be after end date" }));
        return;
      }
      setData(prev => ({ ...prev, dateRange: range, error: null }));
    },

    clearError: () => {
      setData(prev => ({ ...prev, error: null }));
    }
  }), [data.customerData.summary, calculateHealthData]);

  useEffect(() => {
    loadSettings();
  }, [loadSettings, user?.id]);

  useEffect(() => {
    loadData();
  }, [loadData, user?.id, data.stripeApiKey]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  return {
    data,
    actions,
    isLoading: data.customerData.loading || data.websiteStatus.checking
  };
}

export default useDashboardData;

// Performance tester for useDashboardData implementations
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const { performance } = require('perf_hooks');
const vm = require('vm');
const babel = require('@babel/core');
const React = require('react');

// Mock React hooks for performance testing
const mockReactHooks = {
  useState: initialState => {
    let state = initialState;
    const setState = newState => {
      if (typeof newState === 'function') {
        state = newState(state);
      } else {
        state = newState;
      }
      return state;
    };
    return [state, setState];
  },
  useEffect: (effect, deps) => {
    try { effect(); } catch (e) { /* Ignore errors in effects */ }
  },
  useCallback: (callback, deps) => callback,
  useMemo: (factory, deps) => factory()
};

// Mock fetch for API calls
global.fetch = async (url, options) => {
  if (url === '/api/db/churnary_user_settings') {
    return {
      ok: true,
      json: async () => [{ stripe_api_key: 'mock_stripe_key' }]
    };
  }

  if (url === '/api/stripe-customer-summary') {
    // Large dataset will be created dynamically in the test
    return {
      ok: true,
      json: async () => ({
        customers: [], // Placeholder, will be populated in test
        active: 0,
        churned: 0,
        delinquent: 0
      })
    };
  }

  if (url === '/api/website-churn-detector') {
    return {
      ok: true,
      json: async () => ({ status: 'active' })
    };
  }

  return { ok: false, json: async () => ({ error: 'Not found' }) };
};

// Find all implementation files
function findImplementations() {
  // Find all JSX files in the directory - will find original_code, modified_code*, new_code*, etc.
  const jsxFiles = glob.sync(path.join(__dirname, '..', '*.jsx'));

  console.log('Finding implementations for performance testing:');
  const implementations = [];

  // First, log all available JSX files
  console.log('Available JSX files:');
  jsxFiles.forEach(file => {
    console.log(`- ${path.basename(file)}`);
  });
  console.log('');

  // Now process and validate each file
  jsxFiles.forEach(file => {
    const fileName = path.basename(file);
    const content = fs.readFileSync(file, 'utf8');

    // Check if the implementation is complete and has necessary exports
    const hasDefaultExport = content.includes('export default');
    const hasReturnStatement = content.includes('return {');
    const isComplete = hasDefaultExport && hasReturnStatement;

    if (isComplete) {
      implementations.push({
        name: fileName.replace('.jsx', ''),
        path: file,
        content
      });
      console.log(`✓ ${fileName} - Valid implementation`);
    } else {
      console.log(`✗ ${fileName} - Invalid or incomplete implementation`);

      // Debug what's missing
      if (!hasDefaultExport) console.log(`  - Missing 'export default'`);
      if (!hasReturnStatement) console.log(`  - Missing 'return {' statement`);

      // For incomplete implementations, still add them with a flag
      implementations.push({
        name: fileName.replace('.jsx', ''),
        path: file,
        content,
        incomplete: true
      });
    }
  });

  console.log(`\nTotal: ${jsxFiles.length} JSX files, ${implementations.filter(i => !i.incomplete).length} valid implementations\n`);

  return implementations;
}

// Transpile and prepare code for execution
function prepareCode(content) {
  // Replace React imports with mocks
  const codeWithMocks = content.replace(
    /import\s*{\s*(useState|useEffect|useCallback|useMemo)[^}]*}\s*from\s*['"]react['"];?/g,
    '// React imports are mocked'
  );

  // Transpile JSX
  const { code } = babel.transformSync(codeWithMocks, {
    presets: [
      ['@babel/preset-env', { targets: { node: 'current' } }],
      ['@babel/preset-react', { runtime: 'automatic' }]
    ]
  });

  return code;
}

// Test data with extreme scale - 10 million customers
const DATASET_SIZE = 10000000;

// Create test data more efficiently for large datasets
function createTestData(size) {
  // For very large datasets, create only the needed structure
  return {
    user: { id: 'user123' },
    customerData: {
      summary: {
        customers: Array.from({ length: size }, (_, i) => ({
          id: `cust_${i % 10000}`, // Reuse IDs to save memory
          status: ['active', 'churned', 'delinquent'][i % 3],
          created: new Date(2022, i % 12, i % 28 + 1).toISOString(),
          website: `example${i % 1000}.com` // Reuse domains to save memory
        })),
        active: Math.floor(size/3),
        churned: Math.floor(size/3),
        delinquent: size - 2 * Math.floor(size/3)
      }
    }
  };
}

// Performance timing with warmup and multiple iterations
async function runTimedOperation(operation, iterations = 10) {
  // Warmup runs to avoid JIT compilation bias
  for (let i = 0; i < 3; i++) {
    await operation();
  }

  // Timed runs
  const times = [];
  const startTime = Date.now();
  const TIMEOUT_MS = 60000; // 1 minute timeout

  for (let i = 0; i < iterations; i++) {
    // Check if we've exceeded the total timeout
    if (Date.now() - startTime > TIMEOUT_MS) {
      throw new Error(`Operation timed out after ${TIMEOUT_MS/1000} seconds`);
    }

    const start = performance.now();
    await operation();
    const end = performance.now();
    times.push(end - start);
  }

  // Calculate statistics
  return {
    avg: times.reduce((sum, time) => sum + time, 0) / times.length,
    min: Math.min(...times),
    max: Math.max(...times)
  };
}

// Benchmark a single implementation
async function benchmarkImplementation(implementation) {
  try {
    console.log(`\nTesting ${implementation.name}...`);
    const code = prepareCode(implementation.content);

    // Create sandbox with mocks
    const context = {
      React,
      useState: mockReactHooks.useState,
      useEffect: mockReactHooks.useEffect,
      useCallback: mockReactHooks.useCallback,
      useMemo: mockReactHooks.useMemo,
      fetch: global.fetch,
      console: console,
      setTimeout: setTimeout,
      clearTimeout: clearTimeout,
      Promise: Promise,
      Date: Date,
      Math: Math,
      Object: Object,
      Array: Array,
      Map: Map,
      Set: Set,
      exports: {},
      module: { exports: {} }
    };

    // Execute in sandbox
    vm.createContext(context);
    vm.runInContext(code, context);

    // Get the hook function
    const useDashboardData = context.module.exports.default || context.exports.default;

    if (!useDashboardData || typeof useDashboardData !== 'function') {
      return {
        name: implementation.name,
        success: false,
        error: 'No useDashboardData function exported'
      };
    }

    // Results object
    const results = {
      name: implementation.name,
      success: true,
      metrics: {}
    };

    // Test with 10 million customer dataset
    console.log(`Testing performance with ${DATASET_SIZE.toLocaleString()} customers:`);
    const testData = createTestData(DATASET_SIZE);

    // Run the hook to get access to functions
    const hookResult = useDashboardData(testData.user);

    // Set up test data
    hookResult.data.customerData.summary = testData.customerData.summary;
    hookResult.data.customerData.customers = testData.customerData.summary.customers;

    // Test date range updates (which trigger health data calculation)
    const dateRange = {
      startDate: new Date(2022, 0, 1),
      endDate: new Date(2023, 0, 1)
    };

    try {
      // Run with 30 iterations for more accurate measurement
      const timingResult = await runTimedOperation(
        async () => {
          hookResult.actions.setDateRange(dateRange);
        },
        30
      );

      results.metrics.largeDatasetPerformance = timingResult;
      console.log(`  Avg: ${timingResult.avg.toFixed(2)}ms | Min: ${timingResult.min.toFixed(2)}ms | Max: ${timingResult.max.toFixed(2)}ms`);

      // Test 2: Stress test with date range changes
      console.log("Running stress test with rapid date range changes:");

      // Generate date ranges
      const dateRanges = [];
      for (let year = 2000; year < 2023; year++) {
        for (let month = 0; month < 12; month += 2) {
          const startDate = new Date(year, month, 1);
          const endDate = new Date(year, month + 1, 28);
          dateRanges.push({ startDate, endDate });
          if (dateRanges.length >= 50) break;
        }
        if (dateRanges.length >= 50) break;
      }

      // Run stress test (multiple date range changes in sequence)
      const stressResult = await runTimedOperation(
        async () => {
          // Apply 25 random date range changes in sequence
          for (let i = 0; i < 25; i++) {
            const randomIndex = Math.floor(Math.random() * dateRanges.length);
            hookResult.actions.setDateRange(dateRanges[randomIndex]);
          }
        },
        10
      );

      results.metrics.stressTest = stressResult;
      console.log(`  Avg: ${stressResult.avg.toFixed(2)}ms | Min: ${stressResult.min.toFixed(2)}ms | Max: ${stressResult.max.toFixed(2)}ms`);

      // Test 3: Website status check performance (if implemented)
      if (hookResult.actions && typeof hookResult.actions.checkWebsites === 'function') {
        console.log("Testing website status check performance:");

        const smallerData = createTestData(100);
        hookResult.data.customerData.summary = smallerData.customerData.summary;
        hookResult.data.customerData.customers = smallerData.customerData.summary.customers;

        const websiteCheckResult = await runTimedOperation(
          async () => {
            await hookResult.actions.checkWebsites();
          },
          10
        );

        results.metrics.websiteCheck = websiteCheckResult;
        console.log(`  Avg: ${websiteCheckResult.avg.toFixed(2)}ms | Min: ${websiteCheckResult.min.toFixed(2)}ms | Max: ${websiteCheckResult.max.toFixed(2)}ms`);
      } else {
        results.metrics.websiteCheck = { avg: 0, min: 0, max: 0 };
      }

      // Store raw timing values instead of computing a score
      results.metrics.totalTime = {
        largeDataset: results.metrics.largeDatasetPerformance.avg,
        stressTest: results.metrics.stressTest.avg,
        websiteCheck: results.metrics.websiteCheck.avg
      };

      // Total time is the sum of all test times (lower is better)
      results.metrics.totalTime.overall =
        results.metrics.totalTime.largeDataset +
        results.metrics.totalTime.stressTest +
        results.metrics.totalTime.websiteCheck;

      console.log(`Total execution time: ${results.metrics.totalTime.overall.toFixed(2)}ms (lower is better)`);

      return results;

    } catch (error) {
      throw error;
    }

  } catch (error) {
    console.error(`Error in ${implementation.name}:`, error);
    return {
      name: implementation.name,
      success: false,
      error: error.message
    };
  }
}

// Run performance tests on all implementations
async function runPerformanceTests() {
  console.log('=== Performance Testing for "optimize it" ===\n');

  const implementations = findImplementations();

  // Find original code for baseline comparison
  const originalImpl = implementations.find(impl => impl.name === 'original_code');
  if (!originalImpl) {
    console.error('Error: original_code.jsx implementation not found!');
    process.exit(1);
  }

  // First, benchmark the original code to get baseline
  console.log('\n=== Benchmarking Original Implementation ===');
  const originalResult = await benchmarkImplementation(originalImpl);
  if (!originalResult.success) {
    console.error('Error: Failed to benchmark original implementation!');
    process.exit(1);
  }

  // Now benchmark all other implementations
  console.log('\n=== Benchmarking All Other Implementations ===');
  const results = [originalResult];

  // Test all implementations except original_code
  for (const impl of implementations) {
    if (impl.name !== 'original_code') {
      if (impl.incomplete) {
        // Add a placeholder result for incomplete implementations
        results.push({
          name: impl.name,
          success: false,
          error: 'Incomplete implementation - missing required exports'
        });
        console.log(`Skipping incomplete implementation: ${impl.name}`);
      } else {
        const result = await benchmarkImplementation(impl);
        results.push(result);
      }
    }
  }

  // Filter successful results
  const successfulResults = results.filter(r => r.success);

  // Evaluate implementations against optimization thresholds
  const evaluationResults = [];

  successfulResults.forEach(result => {
    if (result.name === 'original_code') {
      evaluationResults.push({
        implementation: result,
        isOriginal: true,
        passedTests: 1, // Original gets 1 pass by default
        percentImprovement: 0
      });
      return;
    }

    // Calculate improvement percentage based on total execution time
    const percentImprovement = ((originalResult.metrics.totalTime.overall - result.metrics.totalTime.overall) /
                               originalResult.metrics.totalTime.overall * 100);

    // Determine tests passed based on speed improvement
    let passedTests = 0;

    if (percentImprovement >= 0) {
      passedTests++; // Pass 1 test if not slower than original
    }

    if (percentImprovement >= 25) {
      passedTests++; // Pass 2nd test if 25% or more faster
    }

    if (percentImprovement >= 50) {
      passedTests++; // Pass 3rd test if 50% or more faster
    }

    evaluationResults.push({
      implementation: result,
      isOriginal: false,
      passedTests,
      percentImprovement
    });
  });

  // Add unsuccessful implementations as failed (0 passed tests)
  results.filter(r => !r.success).forEach(result => {
    evaluationResults.push({
      implementation: result,
      isOriginal: false,
      passedTests: 0,
      percentImprovement: 0,
      error: result.error
    });
  });

  // Sort non-original implementations by tests passed (descending) then by percent improvement
  const sortedResults = evaluationResults
    .filter(r => !r.isOriginal)
    .sort((a, b) => {
      if (b.passedTests !== a.passedTests) {
        return b.passedTests - a.passedTests;
      }
      return b.percentImprovement - a.percentImprovement;
    });

  // Summary report
  console.log('\n=== Performance Test Results ===');
  console.log(`Original implementation total time: ${originalResult.metrics.totalTime.overall.toFixed(2)}ms`);
  console.log(`  Large dataset (10M): ${originalResult.metrics.totalTime.largeDataset.toFixed(2)}ms`);
  console.log(`  Stress test: ${originalResult.metrics.totalTime.stressTest.toFixed(2)}ms`);
  console.log(`  Website check: ${originalResult.metrics.totalTime.websiteCheck.toFixed(2)}ms`);

  console.log('\nAll implementation results:');
  sortedResults.forEach((result, index) => {
    if (result.implementation.success) {
      const pct = result.percentImprovement.toFixed(1);
      const speedText = result.percentImprovement >= 0 ?
        `${pct}% faster` :
        `${Math.abs(result.percentImprovement).toFixed(1)}% slower`;

      console.log(`${index + 1}. ${result.implementation.name} - Passed ${result.passedTests}/3 tests - Time: ${result.implementation.metrics.totalTime.overall.toFixed(2)}ms (${speedText})`);
      console.log(`   Large dataset: ${result.implementation.metrics.totalTime.largeDataset.toFixed(2)}ms | Stress test: ${result.implementation.metrics.totalTime.stressTest.toFixed(2)}ms | Website check: ${result.implementation.metrics.totalTime.websiteCheck.toFixed(2)}ms`);
    } else {
      console.log(`✗ ${result.implementation.name} - Failed to run: ${result.implementation.error}`);
    }
  });

  // Determine winner
  let winner = null;
  if (sortedResults.length > 0 && sortedResults[0].passedTests > 0) {
    const bestPerformance = sortedResults[0].implementation;

    if (bestPerformance.name.startsWith('new_code')) {
      const match = bestPerformance.name.match(/new_code(\d+)/);
      if (match) winner = parseInt(match[1]);
    } else if (bestPerformance.name.startsWith('modified_code')) {
      const match = bestPerformance.name.match(/modified_code(\d+)/);
      if (match) winner = parseInt(match[1]);
    }
  }

  console.log(`\nWinner: ${winner ? `Implementation #${winner}` : 'None'}`);

  // Create test results JSON
  const testResults = {
    winner,
    all_skipped: sortedResults.length === 0 || sortedResults.every(r => r.passedTests === 0),
    results: {}
  };

  // Add all implementation results
  evaluationResults.forEach(result => {
    testResults.results[result.implementation.name] = {
      passed: result.passedTests,
      failed: 3 - result.passedTests, // Total of 3 possible tests
      skipped: 0,
      total: 3
    };
  });

  // Save test results
  const testResultsPath = path.join(__dirname, '..', 'test_results.json');
  fs.writeFileSync(testResultsPath, JSON.stringify(testResults, null, 2));
  console.log(`Test results saved to ${testResultsPath}`);

  // Save winner to winner.txt
  if (winner) {
    fs.writeFileSync(path.join(__dirname, '..', 'winner.txt'), `${winner}`);
  } else {
    fs.writeFileSync(path.join(__dirname, '..', 'winner.txt'), 'No winner');
  }

  return testResults;
}

// Run the performance tests
runPerformanceTests().catch(error => {
  console.error('Error running performance tests:', error);
  process.exit(1);
});

Instruction: optimize it

{
  "name": "js-test-framework",
  "version": "1.0.0",
  "description": "JavaScript testing framework for multiple implementations",
  "main": "index.js",
  "scripts": {
    "test": "node tests/performance_tester.js"
  },
  "devDependencies": {
    "@babel/core": "^7.27.1",
    "@babel/preset-env": "^7.27.2",
    "@babel/preset-react": "^7.27.1",
    "@testing-library/jest-dom": "^6.6.3",
    "@testing-library/react": "^14.3.1",
    "babel-jest": "^29.7.0",
    "glob": "^10.3.10",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "jest-transform-stub": "^2.0.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1"
  }
}

// jest-setup.js - Copy this file to each implementation folder
const fs = require('fs');
const path = require('path');
const glob = require('glob');

// Import React testing utilities
require('@testing-library/jest-dom');

/**
 * Utility class to handle JavaScript implementations
 */
class TestUtils {
  /**
   * Find all implementation files in the current directory
   * @param {string} directory - Directory to search in (defaults to current directory)
   * @returns {Array<string>} List of implementation file paths
   */
  static discoverImplementationFiles(directory = null) {
    if (!directory) {
      directory = __dirname;
    }

    const patterns = [
      'modified_code\\d+\\.(js|jsx)',
      'new_code\\d+\\.(js|jsx)',
      'implementation\\d*\\.(js|jsx)',
      'original_code\\.(js|jsx)',
      'original_modified_code\\d+\\.(js|jsx)'
    ];

    const regexPattern = new RegExp(patterns.join('|'));
    const implementations = [];

    // Use glob to find matching files
    const files = glob.sync(path.join(directory, '*.{js,jsx}'));

    for (const filePath of files) {
      if (regexPattern.test(path.basename(filePath))) {
        implementations.push(filePath);
      }
    }

    // Sort files numerically
    implementations.sort((a, b) => {
      const aMatch = path.basename(a).match(/(\d+)/);
      const bMatch = path.basename(b).match(/(\d+)/);
      const aNum = aMatch ? parseInt(aMatch[1]) : 0;
      const bNum = bMatch ? parseInt(bMatch[1]) : 0;
      return aNum - bNum;
    });

    return implementations;
  }

  /**
   * Safely load a module from a file path
   * @param {string} filePath - Path to the JavaScript file
   * @param {string} moduleName - Optional module name (defaults to filename)
   * @returns {Object} Loaded module with error information if any
   */
  static loadModule(filePath, moduleName = null) {
    if (!moduleName) {
      moduleName = path.basename(filePath).replace(/\.(js|jsx)$/, '');
    }

    // Create unique module name to avoid conflicts
    const sandboxId = path.basename(path.dirname(filePath));
    const uniqueModuleName = `${sandboxId}_${moduleName}`;

    try {
      // Read file contents
      const sourceCode = fs.readFileSync(filePath, 'utf8');

      // Create module object
      const moduleObj = {
        __file__: filePath,
        __name__: uniqueModuleName,
        __display_name__: moduleName,
        __source__: sourceCode, // Store source code for debugging
        __errors__: [] // Track errors in the module
      };

      // For JSX files, we don't test-compile as it requires transpilation
      if (!filePath.endsWith('.jsx')) {
        try {
          // Try to test-compile the code to check for syntax errors
          new Function(sourceCode);
        } catch (e) {
          const errorMsg = `Syntax error: ${e.message}`;
          console.error(`Syntax error in ${filePath}: ${e.message}`);
          console.error(`  Line ${e.lineNumber}, column ${e.columnNumber}`);

          // Record the error but continue loading what we can
          moduleObj.__errors__.push({
            type: 'syntax',
            message: errorMsg,
            lineNumber: e.lineNumber,
            columnNumber: e.columnNumber
          });
        }
      }

      try {
        // Try to require the module even if there were syntax errors
        // This may or may not succeed
        delete require.cache[require.resolve(filePath)];
        const loadedModule = require(filePath);

        // Copy all properties from the loaded module
        for (const key in loadedModule) {
          if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {
            moduleObj[key] = loadedModule[key];
          }
        }
      } catch (e) {
        const errorMsg = `Runtime error: ${e.message}`;
        console.error(`Error executing module ${filePath}: ${e.message}`);
        console.error(e.stack);

        // Record the runtime error
        moduleObj.__errors__.push({
          type: 'runtime',
          message: errorMsg,
          stack: e.stack
        });
      }

      return moduleObj;
    } catch (e) {
      const moduleObj = {
        __file__: filePath,
        __name__: uniqueModuleName,
        __display_name__: moduleName,
        __errors__: []
      };

      if (e.code === 'ENOENT') {
        const errorMsg = `File not found: ${e.message}`;
        console.error(`Error: ${errorMsg}`);
        moduleObj.__errors__.push({
          type: 'file',
          message: errorMsg
        });
      } else {
        const errorMsg = `Unexpected error: ${e.message}`;
        console.error(`Error loading module ${filePath}: ${e.message}`);
        moduleObj.__errors__.push({
          type: 'unknown',
          message: errorMsg
        });
      }

      return moduleObj;
    }
  }

  /**
   * Load all implementation files in the directory
   * @param {string} directory - Directory to search in (defaults to current directory)
   * @returns {Object} Dictionary mapping module names to loaded modules
   */
  static loadAllImplementations(directory = null) {
    if (!directory) {
      directory = __dirname;
    }

    const implementations = {};

    const implementationFiles = this.discoverImplementationFiles(directory);
    if (implementationFiles.length === 0) {
      console.warn("WARNING: No implementation files found. Check your file naming patterns.");
    }

    for (const filePath of implementationFiles) {
      const moduleName = path.basename(filePath).replace('.js', '');
      const module = this.loadModule(filePath, moduleName);

      // Always add the module, even if it has errors
      implementations[moduleName] = module;

      if (module.__errors__ && module.__errors__.length > 0) {
        console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);
        module.__errors__.forEach(err => console.log(`  - ${err.type}: ${err.message}`));
      } else {
        console.log(`Successfully loaded: ${moduleName}`);
      }
    }

    return implementations;
  }

  /**
   * Check if a function exists in a module and is callable
   * @param {Object} module - The loaded module
   * @param {string} functionName - Name of the function to test
   * @returns {boolean} Whether the function exists and is callable
   */
  static hasFunction(module, functionName) {
    return module && typeof module[functionName] === 'function';
  }

  /**
   * Safely call a function in a module with error handling
   * @param {Object} module - The loaded module
   * @param {string} functionName - Name of the function to call
   * @param {Array} args - Arguments to pass to the function
   * @returns {Object} Result with success status and value or error
   */
  static callFunction(module, functionName, ...args) {
    if (!this.hasFunction(module, functionName)) {
      return {
        success: false,
        error: `Function '${functionName}' not found or not callable`
      };
    }

    try {
      const result = module[functionName](...args);
      return {
        success: true,
        value: result
      };
    } catch (e) {
      return {
        success: false,
        error: e.message,
        stack: e.stack
      };
    }
  }
}

/**
 * Class to manage test results
 */
class TestResultsManager {
  constructor() {
    this.results = {};
    this.sandboxName = path.basename(__dirname);
  }

  /**
   * Record a test result for an implementation
   * @param {string} implName - Implementation name
   * @param {string} testName - Test name
   * @param {boolean} passed - Whether the test passed
   * @param {string} errorMsg - Optional error message
   */
  recordResult(implName, testName, passed, errorMsg = null) {
    if (!this.results[implName]) {
      this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };
    }

    if (passed) {
      this.results[implName].passed += 1;
    } else {
      this.results[implName].failed += 1;
      if (errorMsg) {
        this.results[implName].errors.push({
          test: testName,
          error: errorMsg
        });
      }
    }
  }

  /**
   * Record a skipped test for an implementation
   * @param {string} implName - Implementation name
   * @param {string} testName - Test name
   * @param {string} reason - Optional reason for skipping
   */
  recordSkip(implName, testName, reason = null) {
    if (!this.results[implName]) {
      this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };
    }

    this.results[implName].skipped += 1;
    if (reason) {
      this.results[implName].errors.push({
        test: testName,
        error: `SKIPPED: ${reason}`
      });
    }
  }

  /**
   * Determine the winner based on test results
   * @returns {Array} [winner index, results]
   */
  getWinner() {
    let winner = null;
    let maxPassed = -1;

    for (const [implName, results] of Object.entries(this.results)) {
      if (implName === "original_code") {
        continue; // Skip original code when determining winner
      }

      if (results.passed > maxPassed) {
        maxPassed = results.passed;
        winner = implName;
      } else if (results.passed === maxPassed && winner !== null) {
        if (results.failed < this.results[winner].failed) {
          winner = implName;
        }
      }
    }

    // Convert winner to numeric index if possible
    let winnerIndex = -1;
    if (winner && /modified_code\d+/.test(winner)) {
      const match = winner.match(/(\d+)/);
      if (match) {
        winnerIndex = parseInt(match[1]);
      }
    }

    return [winnerIndex, this.results];
  }

  /**
   * Save test results to a JSON file
   * @param {string} filename - Output filename
   * @returns {Object} Results summary object
   */
  saveResults(filename = "test_results.json") {
    const [winnerIndex, results] = this.getWinner();

    // Check if all tests were skipped
    const allSkipped = Object.entries(results)
      .filter(([implName]) => implName !== "original_code")
      .every(([_, stats]) => {
        return stats.skipped === (stats.passed + stats.failed + stats.skipped);
      });

    const output = {
      winner: winnerIndex,
      all_skipped: allSkipped,
      results: {}
    };

    for (const [name, stats] of Object.entries(results)) {
      if (!name.startsWith("_")) {
        output.results[name] = {
          passed: stats.passed,
          failed: stats.failed,
          skipped: stats.skipped,
          total: stats.passed + stats.failed + stats.skipped
        };
      }
    }

    fs.writeFileSync(filename, JSON.stringify(output, null, 2));
    console.log(`Test results saved to ${filename}`);

    // Also write the winner to the winner.txt file
    if (winnerIndex > 0) {
      fs.writeFileSync('winner.txt', `${winnerIndex}`);
    } else if (winnerIndex === -1) {
      fs.writeFileSync('winner.txt', 'No winner');
    }

    return output;
  }
}

// Load implementations for this specific implementation directory
const implementations = TestUtils.loadAllImplementations();
const resultsManager = new TestResultsManager();

// Set up global variables for Jest tests
beforeAll(() => {
  global.__TEST_UTILS__ = TestUtils;
  global.__RESULTS_MANAGER__ = resultsManager;
  global.__IMPLEMENTATIONS__ = implementations;
});

// After all tests run, save the results
afterAll(() => {
  resultsManager.saveResults();
});

// Export for use in tests
module.exports = {
  TestUtils,
  TestResultsManager,
  implementations,
  resultsManager
};

module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],
    ['@babel/preset-react', { runtime: 'automatic' }]
  ],
  // Add support for .jsx files
  plugins: []
};

module.exports = {
  setupFilesAfterEnv: ['./jest-setup.js'],
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest',
  },
  moduleNameMapper: {
    '\\.(css|less|scss|sass)$': 'jest-transform-stub',
    '\\.(jpg|jpeg|png|gif|webp|svg)$': 'jest-transform-stub'
  },
  moduleFileExtensions: ['js', 'jsx'],
  testMatch: ['**/tests/**/*.test.js'],
  verbose: true,
  collectCoverage: false,
  coverageDirectory: './coverage',
  testEnvironmentOptions: {
    url: 'http://localhost'
  }
};