import { createFileRoute } from "@tanstack/react-router";
import { convertToModelMessages, streamText, type UIMessage } from "ai";
import { createLovableAiGatewayProvider } from "@/lib/ai-gateway.server";

const SYSTEM_PROMPT = `You are Gatavase AI, the assistant for Gatavase Corporation — a full-stack technology company headquartered in Kampala, Uganda with an office in Doha, Qatar.

What Gatavase does:
- Services: website development, app development, software development, networking, graphics design, computer training, robotics engineering, and Gatavase AI (AI automation, agents, data platforms).
- Products: Kabo Browser, Secure Guard, Gatavase Search, Gatavase Messenger, Gatavase Bolt, Gatavase SUVs, Gatavase Books, Gatavase Podcast, Gatavase Radio.
- Divisions & impact: Gazman Advanced Technologies, Destiny & Divine Foundation, Lil Gazman Music, Gatavase Foundation, community programs.
- Strengths: scalability, security, rapid delivery cycles, AI, mobile, web, blockchain and enterprise systems.
- Contact: gazmanadvancedtechnologies@gmail.com, +256 773 231138 (Kampala, Muyenga-Bukasa Plot 68), +974 3320 1668 (Doha, Abu Nakhla, Al Rayyan).

How to answer:
- Be warm, concise and concrete. Prefer short paragraphs and bullet points.
- Answer questions about services, products, process, industries, timelines and how to get started.
- Never invent prices, client names, or guarantees. If pricing or a firm timeline is asked, explain it depends on scope and invite the visitor to submit a demo request at /demo-request or email the team.
- Point visitors to relevant pages using plain paths such as /gatavase-ai, /app-development, /projects, /blog, /demo-request or /contact.
- If a question is outside Gatavase's work, say so briefly and steer back to how Gatavase can help.`;

async function loadKnowledge(): Promise<string> {
  const url = process.env.SUPABASE_URL;
  const key = process.env.SUPABASE_PUBLISHABLE_KEY;
  if (!url || !key) return "";
  try {
    const res = await fetch(
      `${url}/rest/v1/chatbot_knowledge?select=kind,title,content,category&published=eq.true&limit=100`,
      { headers: { apikey: key } },
    );
    if (!res.ok) return "";
    const rows = (await res.json()) as {
      kind: string;
      title: string;
      content: string;
      category: string;
    }[];
    if (!rows.length) return "";
    return `\n\nCurated knowledge base maintained by the Gatavase team. Prefer these answers when relevant, and quote them faithfully:\n${rows
      .map((r) => `- [${r.kind}/${r.category}] ${r.title}: ${r.content}`)
      .join("\n")}`;
  } catch (error) {
    console.error("knowledge load failed", error);
    return "";
  }
}

export const Route = createFileRoute("/api/chat")({
  server: {
    handlers: {
      POST: async ({ request }) => {
        const { messages } = (await request.json()) as { messages?: unknown };
        if (!Array.isArray(messages)) {
          return new Response("Messages are required", { status: 400 });
        }

        const key = process.env.LOVABLE_API_KEY;
        if (!key) return new Response("AI is not configured", { status: 500 });

        try {
          const gateway = createLovableAiGatewayProvider(key);
          const knowledge = await loadKnowledge();
          const result = streamText({
            model: gateway("google/gemini-3.6-flash"),
            system: SYSTEM_PROMPT + knowledge,
            messages: await convertToModelMessages(messages as UIMessage[]),
          });
          return result.toUIMessageStreamResponse({
            originalMessages: messages as UIMessage[],
          });
        } catch (error) {
          console.error("chat failed", error);
          return new Response("The assistant is unavailable right now.", { status: 502 });
        }
      },
    },
  },
});
