Code viewer for World: AI API Comparison Tool. (c...

// Cloned by Adam on 3 Dec 2024 from World "AI API Comparison Tool." by Vignesh 
// Please leave this clone trail here.
 
// Create HTML content and add it to the document body
document.body.innerHTML = `
    <h1>Chess Move Fetcher</h1>
    <label for="fen-select">Choose a position:</label>
    <select id="fen-select">
        <option value="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1">Starting Position</option>
        <option value="rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1">King's Pawn Opening</option>
        <option value="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1">Black to Move (Starting Position)</option>
    </select>
    <label for="fen-input">Or Enter FEN:</label>
    <input type="text" id="fen-input" placeholder="Custom FEN here" value="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1">
    <button id="fetch-moves-button">Get Best Moves</button>
    
    <div id="results">
        <h2>Results:</h2>
        <div id="lichess-results"></div>
        <div id="stockfish-results"></div>
    </div>
    <div id="comparison">
        <h2>Comparison:</h2>
        <div id="comparison-results"></div>
    </div>
`;

// Attach event listener to the dropdown to update the input box
document.getElementById('fen-select').addEventListener('change', () => {
    const fenSelect = document.getElementById('fen-select').value;
    document.getElementById('fen-input').value = fenSelect;
});

// Attach an event listener to the "Get Best Moves" button
document.getElementById('fetch-moves-button').addEventListener('click', fetchMoves);

// Function to fetch the moves
async function fetchMoves() {
    const fen = document.getElementById('fen-input').value.trim();
    if (!fen) {
        alert('Please enter a valid FEN!');
        return;
    }

    // Clear previous results
    document.getElementById('lichess-results').innerHTML = '';
    document.getElementById('stockfish-results').innerHTML = '';
    document.getElementById('comparison-results').innerHTML = '';

    try {
        console.log("Fetching moves...");

        // Fetch results from both APIs
        const [lichessData, stockfishData] = await Promise.all([
            getLichessMove(fen),
            getStockfishMove(fen),
        ]);

        console.log("Lichess Data:", lichessData);
        console.log("Stockfish Data:", stockfishData);

        // Display the results
        displayResults(lichessData, stockfishData);

        // Compare the results
        compareResults(lichessData, stockfishData);
    } catch (error) {
        console.error('Error fetching moves:', error);
        alert('An error occurred while fetching moves. Check the console for more details.');
    }
}

// Function to call the Lichess API and get the best move
async function getLichessMove(fen) {
    const response = await fetch(`https://lichess.org/api/cloud-eval?fen=${encodeURIComponent(fen)}`);
    if (!response.ok) throw new Error('Lichess API request failed');
    const data = await response.json();
    return data;
}

// Mock Stockfish API function (replace this with a real API endpoint if available)
async function getStockfishMove(fen) {
    // Mock response for demonstration purposes
    return {
        bestMove: "e2e4",
        evaluation: 50,
    };
}

// Function to display the results
function displayResults(lichessData, stockfishData) {
    const lichessBestMoves = lichessData.pvs ? lichessData.pvs[0].moves : 'No moves available';
    const lichessEval = lichessData.pvs ? lichessData.pvs[0].cp : 'No evaluation available';

    document.getElementById('lichess-results').innerHTML = `
        <h3>Lichess Results:</h3>
        <p><strong>Best Moves:</strong> ${lichessBestMoves}</p>
        <p><strong>Evaluation:</strong> ${lichessEval} centipawns</p>
    `;

    document.getElementById('stockfish-results').innerHTML = `
        <h3>Stockfish Results:</h3>
        <p><strong>Best Move:</strong> ${stockfishData.bestMove}</p>
        <p><strong>Evaluation:</strong> ${stockfishData.evaluation} centipawns</p>
    `;
}

// Function to compare the results
function compareResults(lichessData, stockfishData) {
    const lichessBestMoves = lichessData.pvs ? lichessData.pvs[0].moves.split(' ') : [];
    const stockfishBestMove = stockfishData.bestMove;

    const isMatch = lichessBestMoves.includes(stockfishBestMove);
    const comparisonResult = isMatch
        ? "Lichess and Stockfish agree on the best move!"
        : "Lichess and Stockfish disagree on the best move.";

    document.getElementById('comparison-results').innerHTML = `
        <p>${comparisonResult}</p>
    `;
}