const BOOKS = {
  fantasy: [
    { title: 'The Name of the Wind', author: 'Patrick Rothfuss' },
    { title: 'The Way of Kings', author: 'Brandon Sanderson' },
    { title: 'A Wizard of Earthsea', author: 'Ursula K. Le Guin' },
    { title: 'The Lies of Locke Lamora', author: 'Scott Lynch' },
  ],
  'sci-fi': [
    { title: 'Dune', author: 'Frank Herbert' },
    { title: 'Neuromancer', author: 'William Gibson' },
    { title: 'The Left Hand of Darkness', author: 'Ursula K. Le Guin' },
    { title: 'Project Hail Mary', author: 'Andy Weir' },
  ],
  mystery: [
    { title: 'The Girl with the Dragon Tattoo', author: 'Stieg Larsson' },
    { title: 'Gone Girl', author: 'Gillian Flynn' },
    { title: 'The Da Vinci Code', author: 'Dan Brown' },
    { title: 'Big Little Lies', author: 'Liane Moriarty' },
  ],
  default: [
    { title: 'To Kill a Mockingbird', author: 'Harper Lee' },
    { title: '1984', author: 'George Orwell' },
    { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
    { title: 'Sapiens', author: 'Yuval Noah Harari' },
  ],
};

const suggestBooksTool = {
  type: 'function',
  function: {
    name: 'suggest_books',
    description: 'Return book suggestions.',
    parameters: {
      type: 'object',
      properties: {
        genre: {
          type: 'string',
          description: 'The book genre or topic.',
        },
      },
      required: ['genre'],
      additionalProperties: false,
    },
  },
};

const tools = {
  suggest_books: ({ genre }) => BOOKS[genre.toLowerCase()] || BOOKS.default,
};

async function handleToolCalls(first, messages) {
  if (!first.message.tool_calls?.length) return messages;

  const updated = [...messages, first.message];

  for (const call of first.message.tool_calls) {
    const fn = tools[call.function.name];
    const result = fn?.(call.function.arguments) ?? { error: 'Unknown tool' };
    updated.push({ role: 'tool', content: JSON.stringify(result) });
  }

  return updated;
}

export { suggestBooksTool, handleToolCalls };
