/**
 * LLM routing endpoints for cowork-service.
 *
 * POST /api/llm/chat     — Route a chat completion through the LLM router
 * GET  /api/llm/providers — List available LLM providers
 * GET  /api/llm/health    — Health snapshots for all provider+model pairs
 *
 * All endpoints are gated by the `llm_multi_model_enabled` feature flag.
 */

import type { FastifyInstance } from 'fastify';
import { isFeatureEnabled } from '../../lib/feature-flags.js';
import { getLlmRouter, isLlmRouterReady } from '../../lib/llm-router.js';
import { ChatRequestSchema } from './types.js';

export async function llmRoutes(app: FastifyInstance) {
  // ── POST /api/llm/chat ───────────────────────────────────────
  app.post('/api/llm/chat', async (req, reply) => {
    if (!isFeatureEnabled('llm_multi_model_enabled')) {
      reply.code(403);
      return { error: 'LLM multi-model routing is disabled' };
    }

    if (!isLlmRouterReady()) {
      reply.code(503);
      return { error: 'LLM router not initialized — no providers configured' };
    }

    const parsed = ChatRequestSchema.safeParse(req.body);
    if (!parsed.success) {
      reply.code(400);
      return { error: 'Invalid request', details: parsed.error.issues };
    }

    try {
      const result = await getLlmRouter().chat(parsed.data);
      return {
        response: result.response,
        provider: result.provider,
        model: result.model,
        totalLatencyMs: result.totalLatencyMs,
        attempts: result.attempts,
      };
    } catch (err) {
      req.log.error(err, 'LLM chat routing failed');
      reply.code(502);
      return { error: err instanceof Error ? err.message : 'LLM routing failed' };
    }
  });

  // ── GET /api/llm/providers ──────────────────────────────────
  app.get('/api/llm/providers', async (_req, reply) => {
    if (!isFeatureEnabled('llm_multi_model_enabled')) {
      reply.code(403);
      return { error: 'LLM multi-model routing is disabled' };
    }

    if (!isLlmRouterReady()) {
      return { providers: [], ready: false };
    }

    return {
      providers: getLlmRouter().getProviders(),
      ready: true,
    };
  });

  // ── GET /api/llm/health ─────────────────────────────────────
  app.get('/api/llm/health', async (_req, reply) => {
    if (!isFeatureEnabled('llm_multi_model_enabled')) {
      reply.code(403);
      return { error: 'LLM multi-model routing is disabled' };
    }

    if (!isLlmRouterReady()) {
      return { snapshots: [], ready: false };
    }

    return {
      snapshots: getLlmRouter().getHealth(),
      ready: true,
    };
  });
}
