/**
 * suggestions-svc — AI follow-up suggestions
 * API: POST /api/v1/suggestions
 */

import Fastify from 'fastify';
import cors from '@fastify/cors';
import { z } from 'zod';
import { loadChatModel } from './lib/models/registry.js';
import { generateSuggestions } from './lib/agents/suggestions.js';

const PORT = parseInt(process.env.PORT ?? '3017', 10);

const chatModelSchema = z.object({
  providerId: z.string(),
  key: z.string(),
});

const bodySchema = z.object({
  chatHistory: z.array(z.tuple([z.string(), z.string()])),
  chatModel: chatModelSchema,
  locale: z.string().optional(),
});

const app = Fastify({ logger: true });
await app.register(cors, { origin: true });

app.get('/health', async () => ({ status: 'ok' }));

app.post('/api/v1/suggestions', async (req, reply) => {
  try {
    const parsed = bodySchema.safeParse((req as { body?: unknown }).body);
    if (!parsed.success) {
      return reply.status(400).send({ error: 'Invalid body', details: parsed.error.flatten() });
    }
    const { chatHistory, chatModel, locale } = parsed.data;
    const llm = await loadChatModel(chatModel.providerId, chatModel.key);
    const history = chatHistory.map(([role, content]) => ({
      role: (role === 'human' ? 'user' : 'assistant') as 'user' | 'assistant',
      content,
    }));
    const suggestions = await generateSuggestions({ chatHistory: history, locale }, llm);
    return reply.send({ suggestions });
  } catch (err) {
    req.log.error(err);
    const msg = err instanceof Error ? err.message : 'Suggestions generation failed';
    return reply.status(500).send({ error: msg });
  }
});

try {
  await app.listen({ port: PORT, host: '0.0.0.0' });
  console.log(`suggestions-svc listening on :${PORT}`);
} catch (err) {
  console.error(err);
  process.exit(1);
}
