import { NextRequest, NextResponse } from 'next/server';
import { GoogleGenerativeAI } from '@google/generative-ai';
import { adminDb } from '@/lib/firebase-admin';
import { COLLECTIONS } from '@/types/firestore';
import { verifyMember } from '@/lib/auth-middleware';

// Cosine Similarity helper
function cosineSimilarity(A: number[], B: number[]) {
    let dotProduct = 0;
    let mA = 0;
    let mB = 0;
    for (let i = 0; i < A.length; i++) {
        dotProduct += A[i] * B[i];
        mA += A[i] * A[i];
        mB += B[i] * B[i];
    }
    return dotProduct / (Math.sqrt(mA) * Math.sqrt(mB));
}

export async function POST(req: NextRequest) {
    const authResult = await verifyMember(req);
    if (authResult instanceof NextResponse) return authResult;

    try {
        const { queryVector, queryText, apiKey } = await req.json();

        if (!queryVector || !queryText || !apiKey) {
            return NextResponse.json({ error: 'Missing parameters' }, { status: 400 });
        }

        // 1. Fetch Candidate Vectors (MVP approach: fetch all for now, optimize later)
        // In a real production app with thousands of docs, use a Vector Index.
        // For InsuWiki MVP, we'll fetch embeddings from all documents.
        const allDocsSnap = await adminDb.collectionGroup('embeddings').get();

        const candidates: any[] = [];
        allDocsSnap.forEach((doc: any) => {
            const data = doc.data();
            const similarity = cosineSimilarity(queryVector, data.vector);
            if (similarity > 0.6) { // Threshold
                candidates.push({
                    content: data.content,
                    docTitle: data.docTitle,
                    docId: doc.ref.parent.parent?.id,
                    similarity
                });
            }
        });

        // 2. Sort by similarity
        candidates.sort((a, b) => b.similarity - a.similarity);
        const topCandidates = candidates.slice(0, 5); // Take top 5 chunks

        if (topCandidates.length === 0) {
            return NextResponse.json({
                answer: "검색된 결과가 위키 내에 없습니다. 구체적인 키워드로 다시 질문해 주세요.",
                sources: []
            });
        }

        // 3. RAG Synthesis via Gemini
        const genAI = new GoogleGenerativeAI(apiKey);
        const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });

        const context = topCandidates.map(c => `[출처: ${c.docTitle}]\n${c.content}`).join('\n\n---\n\n');
        const prompt = `당신은 보험 전문가들의 위키 데이터를 분석하는 AI 상담원입니다. 
아래 제공된 [내부 지식]만을 바탕으로 사용자의 질문에 답변하세요. 
만약 지식에 없는 내용이라면 외부 지식을 빌려 답변하지 말고 "관련 내용을 위키에서 찾을 수 없습니다"라고 답하세요.
답변 끝에는 반드시 참고한 문서 제목을 언급하세요.

[내부 지식]
${context}

사용자 질문: ${queryText}

AI 답변:`;

        const result = await model.generateContent(prompt);
        const answer = result.response.text();

        return NextResponse.json({
            answer,
            sources: topCandidates.map(c => ({ title: c.docTitle, id: c.docId }))
        });

    } catch (error: any) {
        console.error('Search API Error:', error);
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}
