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

/**
 * GET /api/dataset/datasets/:datasetId/documents/:documentId/segments/:segmentId/child_chunks - 获取子分段列表
 * Dify API: GET /datasets/{dataset_id}/documents/{document_id}/segments/{segment_id}/child_chunks
 */
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, documentId, segmentId } = params;
        if (!datasetId || !documentId || !segmentId) {
            return new Response(
                JSON.stringify({ error: '缺少必要参数' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

        // 获取查询参数
        const url = new URL(request.url);
        const page = url.searchParams.get('page') || '1';
        const limit = url.searchParams.get('limit') || '20';
        const keyword = url.searchParams.get('keyword') || '';

        console.log('[API] Child Chunks List:', { datasetId, documentId, segmentId, page, limit, keyword });

        // 构建查询参数
        const queryParams = new URLSearchParams({ page, limit });
        if (keyword) queryParams.append('keyword', keyword);

        // 转发请求到 FastAPI -> Dify API
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}/child_chunks?${queryParams}`;
        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] Child Chunks List - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to get child chunks' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}

/**
 * POST /api/dataset/datasets/:datasetId/documents/:documentId/segments/:segmentId/child_chunks - 新增子分段
 * Dify API: POST /datasets/{dataset_id}/documents/{document_id}/segments/{segment_id}/child_chunks
 * 请求体: { content: string }
 */
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, documentId, segmentId } = params;
        if (!datasetId || !documentId || !segmentId) {
            return new Response(
                JSON.stringify({ error: '缺少必要参数' }),
                { 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] Create Child Chunk:', { datasetId, documentId, segmentId });

        // 转发请求到 FastAPI -> Dify API
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}/child_chunks`;
        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] Create Child Chunk - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to create child chunk' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}
