import type { APIRoute } from 'astro';
import { site } from '../config/site';

/**
 * /assistant.json — a copy of the website assistant's knowledge base made at BUILD time.
 * The chat downloads the live list from the API (GET /public/assistant) when it opens; this file is the fallback when the
 * API cannot be reached, so the assistant keeps answering. Never fails the build (empty list if the API is down).
 */
export const GET: APIRoute = async () => {
  let data: unknown = { version: '0', answers: [] };
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(), 6000);
  try {
    const res = await fetch(`${site.buildApiUrl}/public/assistant`, { headers: { Accept: 'application/json' }, signal: ctrl.signal });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    data = (await res.json())?.data ?? data;
  } catch (e) {
    console.warn(`[assistant] knowledge base not loaded (${(e as Error).message}) — /assistant.json is empty`);
  } finally {
    clearTimeout(timer);
  }
  return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json; charset=utf-8' } });
};
