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 - 获取分段列表
 * Dify API: GET /datasets/{dataset_id}/documents/{document_id}/segments
 */
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 } = params;
        if (!datasetId || !documentId) {
            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') || '';
        const status = url.searchParams.get('status') || '';

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

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

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

/**
 * POST /api/dataset/datasets/:datasetId/documents/:documentId/segments - 新增分段（批量）
 * Dify API: POST /datasets/{dataset_id}/documents/{document_id}/segments
 * 请求体: { segments: [{ content, answer?, keywords? }] }
 */
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 } = params;
        if (!datasetId || !documentId) {
            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 Segments:', { datasetId, documentId, segmentsCount: body.segments?.length });

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