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

/**
 * GET /api/dataset/datasets/:datasetId - 获取知识库详情
 * Dify API: GET /datasets/{dataset_id}
 */
export async function loader({ request, params }: LoaderFunctionArgs) {
    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: '缺少 datasetId 参数' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

        console.log('[API] Dataset Detail:', { datasetId });

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

        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] Dataset Detail - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to get dataset' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}

/**
 * PATCH /api/dataset/datasets/:datasetId - 修改知识库详情
 *
 * Dify API: PATCH /datasets/{dataset_id}
 *
 * 请求体示例:
 * {
 *   "name": "知识库名称",
 *   "description": "描述",
 *   "indexing_technique": "high_quality",
 *   "permission": "only_me",
 *   "embedding_model_provider": "zhipuai",
 *   "embedding_model": "embedding-3",
 *   "retrieval_model": {
 *     "search_method": "semantic_search",
 *     "reranking_enable": false,
 *     "top_k": 2,
 *     "score_threshold_enabled": false
 *   }
 * }
 *
 * 注意：删除知识库功能不对外开放
 */
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: '缺少 datasetId 参数' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

        const method = request.method;

        if (method === 'PATCH') {
            // 修改知识库详情
            const body = await request.json();
            console.log('[API] Update Dataset:', { datasetId, body });

            const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}`;
            const response = await fetch(apiUrl, {
                method: 'PATCH',
                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' },
            });
        }

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

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