Code viewer for World: New World
// Ancient Brain World: Compare OpenAI vs DeepSeek on story continuation

// Story dataset
const stories = [
  "The old robot woke up in a junkyard with no memory of how it got there.",
  "A girl found a glowing key that hovered an inch above her hand.",
  "When the storm hit the village, the dogs started barking toward the mountains.",
  "The astronaut saw a message written on the inside of her visor.",
  "The ancient tree whispered a name no one had spoken for centuries.",
  "He opened the dusty book and a strange light filled the room.",
  "The cat sat on the roof, staring at the stars as if it understood them.",
  "A mysterious letter arrived with no return address.",
  "She discovered a hidden door behind the painting in the hallway.",
  "The clock struck thirteen, and something unusual happened in the town."
];

// UI
document.write(`
  <h1>Story Continuation AI Comparison</h1>
  <div style="background:#f9f9f9; padding:20px; border-radius:8px; margin-bottom:20px;">
    <h3>Enter API Keys</h3>
    <label>OpenAI API Key:</label><br>
    <input id="openai_key" type="password" style="width:50vw; padding:8px;"><br><br>
    
    <label>DeepSeek API Key:</label><br>
    <input id="deepseek_key" type="password" style="width:50vw; padding:8px;">
  </div>
  
  <div style="background:#f9f9f9; padding:20px; border-radius:8px; margin-bottom:20px;">
    <h3>Select a story beginning:</h3>
    <select id="story_select" style="width:60vw; padding:10px;">
      ${stories.map((s,i) => `<option value="${i}">${s}</option>`).join('')}
    </select>
    <br><br>
    <button onclick="compareAI()" class="ab-normbutton">Compare Models</button>
  </div>
  
  <div style="width:70vw; background:#f0f0f0; padding:20px; border:1px solid black;">
    <h3>Results</h3>
    <div id="results">Results will appear here after running comparison...</div>
  </div>
`);

// Helper function to call OpenAI API
async function callOpenAI(prompt, key) {
  const response = await fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer " + key
    },
    body: JSON.stringify({
      model: "gpt-3.5-turbo",
      messages: [{"role":"user","content": "Continue this story in 2-3 sentences: " + prompt}],
      temperature: 0.7
    })
  });
  
  if (!response.ok) {
    throw new Error("OpenAI API error: " + response.status);
  }
  
  const data = await response.json();
  return data.choices[0].message.content;
}

// Helper function to call DeepSeek API
async function callDeepSeek(prompt, key) {
  const response = await fetch("https://api.deepseek.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer " + key
    },
    body: JSON.stringify({
      model: "deepseek-chat",
      messages: [{"role":"user","content": "Continue this story in 2-3 sentences: " + prompt}],
      temperature: 0.7
    })
  });
  
  if (!response.ok) {
    throw new Error("DeepSeek API error: " + response.status);
  }
  
  const data = await response.json();
  return data.choices[0].message.content;
}

// Helper function to score text using OpenAI as judge
async function scoreText(story, continuation, key) {
  const judgePrompt = `You are a writing evaluator. The story beginning is: "${story}"
The continuation is: "${continuation}"

Score the output on 3 criteria:
- Coherence (0-2)
- Creativity (0-2)
- Grammar (0-1)

Return ONLY a JSON object in this exact format:
{"coherence": X, "creativity": Y, "grammar": Z, "total": T}`;

  const response = await fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer " + key
    },
    body: JSON.stringify({
      model: "gpt-3.5-turbo",
      messages: [{"role":"user","content": judgePrompt}],
      temperature: 0
    })
  });
  
  const data = await response.json();
  let content = data.choices[0].message.content;
  
  // Try to extract JSON if wrapped in markdown
  const jsonMatch = content.match(/\{[^}]+\}/);
  if (jsonMatch) {
    content = jsonMatch[0];
  }
  
  try {
    return JSON.parse(content);
  } catch(e) {
    console.error("Failed to parse score:", content);
    return {coherence: 0, creativity: 0, grammar: 0, total: 0};
  }
}

// Main function
async function compareAI() {
  const openaiKey = document.getElementById("openai_key").value.trim();
  const deepseekKey = document.getElementById("deepseek_key").value.trim();
  const storyIndex = document.getElementById("story_select").value;
  const story = stories[storyIndex];
  const resultsDiv = document.getElementById("results");
  
  // Validate inputs
  if (!openaiKey) {
    resultsDiv.innerHTML = '<b style="color:red;">Please enter your OpenAI API key</b>';
    return;
  }
  if (!deepseekKey) {
    resultsDiv.innerHTML = '<b style="color:red;">Please enter your DeepSeek API key</b>';
    return;
  }
  
  resultsDiv.innerHTML = "⏳ Running AI comparison... This may take 10-20 seconds...";
  
  try {
    // Run both AIs in parallel
    const [openAIText, deepseekText] = await Promise.all([
      callOpenAI(story, openaiKey),
      callDeepSeek(story, deepseekKey)
    ]);
    
    resultsDiv.innerHTML = "⏳ Scoring results...";
    
    // Score both using OpenAI judge
    const [scoreOpen, scoreDeepSeek] = await Promise.all([
      scoreText(story, openAIText, openaiKey),
      scoreText(story, deepseekText, openaiKey)
    ]);
    
    // Determine winner
    let winner = "🤝 It's a Tie!";
    if (scoreOpen.total > scoreDeepSeek.total) {
      winner = "🏆 OpenAI Wins!";
    } else if (scoreDeepSeek.total > scoreOpen.total) {
      winner = "🏆 DeepSeek Wins!";
    }
    
    // Display results
    resultsDiv.innerHTML = `
      <b>Story Beginning:</b><br>
      <em>${story}</em><br><br>
      
      <div style="background:white; padding:15px; margin:10px 0; border-radius:5px;">
        <b>OpenAI Continuation:</b><br>
        ${openAIText}<br><br>
        <b>Score:</b> Coherence: ${scoreOpen.coherence}/2, Creativity: ${scoreOpen.creativity}/2, Grammar: ${scoreOpen.grammar}/1 
        <br><b>Total: ${scoreOpen.total}/5</b>
      </div>
      
      <div style="background:white; padding:15px; margin:10px 0; border-radius:5px;">
        <b>DeepSeek Continuation:</b><br>
        ${deepseekText}<br><br>
        <b>Score:</b> Coherence: ${scoreDeepSeek.coherence}/2, Creativity: ${scoreDeepSeek.creativity}/2, Grammar: ${scoreDeepSeek.grammar}/1
        <br><b>Total: ${scoreDeepSeek.total}/5</b>
      </div>
      
      <h3 style="color:green;">${winner}</h3>
    `;
    
  } catch(e) {
    resultsDiv.innerHTML = `<b style="color:red;">Error: ${e.message}</b><br><br>
    Please check:<br>
    - Your API keys are valid<br>
    - You have sufficient credits<br>
    - Your network connection<br><br>
    Console error: ${e}`;
    console.error("Full error:", e);
  }
}