/**
 * Knowledge Search Edge Function
 *
 * 项目知识库 RAG 检索：把查询文本向量化后从 knowledge_base 表搜出相似条目。
 * Embedding 走 AI 中台（OpenAI 兼容 /v1/embeddings）。
 *
 * Body: { query: string, category?: string, limit?: number, min_similarity?: number }
 * Resp: { results: [...], count }
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.45.0';
import { generateEmbedding } from '../_shared/aiProvider.ts';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
};

interface SearchRequest {
  query: string;
  category?: string;
  limit?: number;
  min_similarity?: number;
}

Deno.serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
  const SUPABASE_SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;

  try {
    const body: SearchRequest = await req.json();
    const { query, category, limit = 5, min_similarity = 0.5 } = body;

    if (!query || typeof query !== 'string') {
      return new Response(
        JSON.stringify({ error: 'Missing query', results: [] }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    console.log('🔍 Knowledge search:', { query, category, limit });

    let embedding: number[];
    try {
      embedding = await generateEmbedding(query);
    } catch (err) {
      console.error('❌ AI Hub embedding error:', err);
      return new Response(
        JSON.stringify({
          error: `Embedding failed: ${err instanceof Error ? err.message : String(err)}`,
          results: [],
        }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
    const { data, error } = await supabase.rpc('search_knowledge_base', {
      query_embedding: embedding,
      match_count: limit,
      filter_category: category ?? null,
      min_similarity,
    });

    if (error) {
      console.error('❌ RPC error:', error);
      return new Response(
        JSON.stringify({ error: (error instanceof Error ? error.message : String(error)), results: [] }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    console.log('✅ Found', data?.length || 0, 'matches');

    return new Response(
      JSON.stringify({ results: data || [], count: data?.length || 0 }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  } catch (error) {
    console.error('❌ knowledge-search error:', error);
    return new Response(
      JSON.stringify({
        error: (error instanceof Error ? error.message : 'Unknown error'),
        results: [],
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
