import { type ActionFunctionArgs } from '@remix-run/node';
import { API_BASE_URL } from '~/config/api-config';

/**
 * POST /api/dataset/datasets/:datasetId/retrieve - 检索知识库
 * Dify API: POST /datasets/{dataset_id}/retrieve
 *
 * 请求体:
 * {
 *   query: string,                          // 检索关键词
 *   retrieval_model?: {
 *     search_method: 'keyword_search' | 'semantic_search' | 'full_text_search' | 'hybrid_search',
 *     reranking_enable?: boolean,
 *     reranking_model?: {
 *       reranking_provider_name: string,
 *       reranking_model_name: string
 *     },
 *     top_k?: number,
 *     score_threshold_enabled?: boolean,
 *     score_threshold?: number
 *   },
 *   metadata_filtering_conditions?: {
 *     logical_operator: 'and' | 'or',
 *     conditions: Array<{
 *       name: string,
 *       comparison_operator: string,
 *       value?: string | number
 *     }>
 *   }
 * }
 */
export async function action({ request, params }: ActionFunctionArgs) {
    try {
        const { getUserSession } = await import("~/api/login/auth.server");
        const { frontendJWT } = await getUserSession(request);

        if (!frontendJWT) {
            return new Response(
                JSON.stringify({ error: 'JWT认证失败，请重新登录' }),
                { status: 401, headers: { 'Content-Type': 'application/json' } }
            );
        }

        const { datasetId } = params;
        if (!datasetId) {
            return new Response(
                JSON.stringify({ error: '缺少知识库ID' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

        if (request.method !== 'POST') {
            return new Response(
                JSON.stringify({ error: 'Method not allowed' }),
                { status: 405, headers: { 'Content-Type': 'application/json' } }
            );
        }

        const body = await request.json();
        console.log('[API] Retrieve Dataset:', { datasetId, query: body.query });

        // 转发请求到 FastAPI -> Dify API
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/retrieve`;
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${frontendJWT}`,
            },
            body: JSON.stringify(body),
        });

        const data = await response.json();

        return new Response(JSON.stringify(data), {
            status: response.status,
            headers: { 'Content-Type': 'application/json' },
        });

    } catch (error: any) {
        console.error('[API] Retrieve Dataset - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to retrieve dataset' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}
