/**
 * master-agents-svc — Master Agent с динамическими под-агентами и инструментами
 * API: POST /api/v1/agents/execute
 */

import Fastify from 'fastify';
import cors from '@fastify/cors';
import { z } from 'zod';
import { loadChatModel } from './lib/models/registry.js';
import { runMasterAgent } from './lib/agent/master.js';

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

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

const bodySchema = z.object({
  task: z.string().min(1),
  chatHistory: z.array(z.tuple([z.string(), z.string()])).optional().default([]),
  chatModel: chatModelSchema,
  maxSteps: z.number().min(1).max(25).optional().default(15),
});

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

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

app.post('/api/v1/agents/execute', 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 { task, chatHistory, chatModel, maxSteps } = parsed.data;
    const llm = await loadChatModel(chatModel.providerId, chatModel.key);

    const result = await runMasterAgent(llm, {
      task,
      chatHistory,
      context: {
        chatModel,
        chatHistory,
      },
      maxSteps,
    });

    return reply.send({
      content: result.content,
      steps: result.steps,
    });
  } catch (err) {
    req.log.error(err);
    const msg = err instanceof Error ? err.message : 'Agent execution failed';
    return reply.status(500).send({ error: msg });
  }
});

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