import express from 'express';
import cors from 'cors';
import { Ollama } from 'ollama';
import { suggestBooksTool, handleToolCalls } from './tools.js';

const app = express();
const ollama = new Ollama();

app.use(cors());
app.use(express.json());

const systemPrompt = {
  role: 'system',
  content: 'You are a helpful assistant. When a tool call is required, use it.',
};

app.post('/v1/chat/completions', async (req, res) => {
  const { messages, model = 'llama3.2:1b' } = req.body;

  try {
    const first = await ollama.chat({
      model,
      messages: [systemPrompt, ...messages],
      tools: [suggestBooksTool],
    });

    const finalMessages = await handleToolCalls(first, messages);

    const final = first.message.tool_calls?.length
      ? await ollama.chat({ model, messages: finalMessages })
      : first;

    res.json({
      id: `chatcmpl-${Date.now()}`,
      object: 'chat.completion',
      created: Math.floor(Date.now() / 1000),
      model,
      choices: [
        {
          index: 0,
          message: { role: 'assistant', content: final.message.content },
          finish_reason: 'stop',
        },
      ],
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: { message: err.message } });
  }
});

app.listen(3001, () => console.log('Backend running on http://localhost:3001'));
