import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { CONTENT_PAGES } from "@/lib/site-content";

export interface SearchHit {
  title: string;
  path: string;
  group: string;
  snippet: string;
  score: number;
}

const GATEWAY = "https://ai.gateway.lovable.dev/v1/chat/completions";

const STATIC_PAGES: { title: string; path: string; group: string; text: string }[] = [
  { title: "Home", path: "/", group: "Company", text: "Gatavase Corporation full stack technology company AI mobile web blockchain enterprise" },
  { title: "Welcome universe", path: "/welcome", group: "Company", text: "futuristic AI landing hologram host welcome universe" },
  { title: "About Gatavase", path: "/about", group: "Company", text: "founder story subsidiaries leadership mission Kampala Doha" },
  { title: "Contact", path: "/contact", group: "Company", text: "contact sales support email phone Kampala Doha enquiry" },
  { title: "Demo request", path: "/demo-request", group: "Company", text: "request a demo start a project scoping budget timeline" },
  { title: "Blog", path: "/blog", group: "Company", text: "articles AI automation mobile apps blockchain social impact insights" },
  { title: "Live Podcast", path: "/live-podcast", group: "Products", text: "live stream podcast episodes Q&A broadcast schedule" },
  { title: "Episodes archive", path: "/episodes", group: "Products", text: "past episodes recordings archive show notes guests" },
  { title: "Gatavase Studio", path: "/studio", group: "Products", text: "AI creative suite voice cloning document creation image video generation e-learning training" },
  { title: "GataMail", path: "/gatamail", group: "Products", text: "secure business email custom domain encrypted inbox compose attachments" },
  { title: "ChatBud", path: "/chatbud", group: "Products", text: "chat assistant conversation companion questions support" },
];

function tokenise(value: string) {
  return value
    .toLowerCase()
    .split(/[^a-z0-9+]+/)
    .filter((t) => t.length > 1);
}

export const searchSite = createServerFn({ method: "POST" })
  .inputValidator((input: unknown) =>
    z.object({ query: z.string().trim().min(2).max(200) }).parse(input),
  )
  .handler(async ({ data }) => {
    const terms = tokenise(data.query);

    const docs = [
      ...CONTENT_PAGES.map((p) => ({
        title: p.title,
        path: p.slug,
        group: p.group as string,
        text: [p.title, p.description, p.intro, ...p.bullets, ...p.highlights.map((h) => `${h.title} ${h.body}`)].join(" "),
      })),
      ...STATIC_PAGES,
    ];

    const hits: SearchHit[] = docs
      .map((doc) => {
        const haystack = `${doc.title} ${doc.text}`.toLowerCase();
        let score = 0;
        for (const term of terms) {
          if (doc.title.toLowerCase().includes(term)) score += 6;
          const matches = haystack.split(term).length - 1;
          score += Math.min(matches, 6);
        }
        const idx = terms.length ? haystack.indexOf(terms[0]!) : -1;
        const start = idx > 60 ? idx - 60 : 0;
        return {
          title: doc.title,
          path: doc.path,
          group: doc.group,
          snippet: `${doc.text.slice(start, start + 220).trim()}…`,
          score,
        };
      })
      .filter((h) => h.score > 0)
      .sort((a, b) => b.score - a.score)
      .slice(0, 10);

    // Blog results
    let posts: SearchHit[] = [];
    try {
      const url = process.env.SUPABASE_URL;
      const key = process.env.SUPABASE_PUBLISHABLE_KEY;
      if (url && key) {
        const res = await fetch(
          `${url}/rest/v1/blog_posts?select=title,slug,excerpt,category&published=eq.true&or=(title.ilike.*${encodeURIComponent(data.query)}*,excerpt.ilike.*${encodeURIComponent(data.query)}*)&limit=6`,
          { headers: { apikey: key } },
        );
        if (res.ok) {
          const rows = (await res.json()) as {
            title: string;
            slug: string;
            excerpt: string | null;
            category: string | null;
          }[];
          posts = rows.map((r) => ({
            title: r.title,
            path: `/blog/${r.slug}`,
            group: `Blog · ${r.category ?? "Insights"}`,
            snippet: r.excerpt ?? "",
            score: 5,
          }));
        }
      }
    } catch (err) {
      console.error("blog search failed", err);
    }

    const results = [...hits, ...posts].slice(0, 14);

    // AI-style answer grounded in the matched pages
    let answer = "";
    const key = process.env.LOVABLE_API_KEY;
    if (key && results.length) {
      try {
        const res = await fetch(GATEWAY, {
          method: "POST",
          headers: { "content-type": "application/json", "Lovable-API-Key": key },
          body: JSON.stringify({
            model: "google/gemini-2.5-flash",
            messages: [
              {
                role: "system",
                content:
                  "You are Gatavase Search. Answer the query in 2-4 sentences using ONLY the supplied Gatavase page extracts. Mention the most relevant page paths inline. Never invent prices, clients or guarantees.",
              },
              {
                role: "user",
                content: `Query: ${data.query}\n\nExtracts:\n${results
                  .map((r) => `- ${r.title} (${r.path}): ${r.snippet}`)
                  .join("\n")}`,
              },
            ],
          }),
        });
        if (res.ok) {
          const json = (await res.json()) as { choices?: { message?: { content?: string } }[] };
          answer = json.choices?.[0]?.message?.content?.trim() ?? "";
        }
      } catch (err) {
        console.error("search answer failed", err);
      }
    }

    return { answer, results };
  });
