/**
 * Knowledge Reindex Edge Function
 *
 * 把 knowledge_base 表中尚未生成 embedding 的条目批量向量化。
 * 走 AI 中台（OpenAI 兼容 /v1/embeddings）。
 *
 * Resp: { processed: number, errors: string[] }
 */

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',
};

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')!;

  const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
  const errors: string[] = [];
  let processed = 0;

  try {
    const { data: rows, error: fetchErr } = await supabase
      .from('knowledge_base')
      .select('id, title, content')
      .is('embedding', null)
      .eq('is_active', true)
      .limit(100);

    if (fetchErr) throw fetchErr;
    if (!rows || rows.length === 0) {
      return new Response(
        JSON.stringify({ processed: 0, message: 'Nothing to reindex' }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    console.log(`🔄 Reindexing ${rows.length} entries via AI Hub...`);

    for (const row of rows) {
      try {
        const text = `${row.title}\n\n${row.content}`;
        const embedding = await generateEmbedding(text);

        const { error: updateErr } = await supabase
          .from('knowledge_base')
          .update({ embedding: embedding as unknown as string })
          .eq('id', row.id);

        if (updateErr) {
          errors.push(`${row.id}: update ${updateErr.message}`);
          continue;
        }
        processed++;
      } catch (err) {
        errors.push(`${row.id}: ${err instanceof Error ? err.message : String(err)}`);
      }
    }

    console.log(`✅ Reindexed ${processed}, errors ${errors.length}`);

    return new Response(
      JSON.stringify({ processed, errors }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  } catch (error) {
    console.error('❌ knowledge-reindex error:', error);
    return new Response(
      JSON.stringify({
        error: (error instanceof Error ? error.message : 'Unknown error'),
        processed,
        errors,
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
