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

/**
 * GET /api/dataset/datasets/:datasetId/documents/:batch/indexing-status
 * 获取文档嵌入状态（处理进度）
 *
 * Dify API: GET /datasets/{dataset_id}/documents/{batch}/indexing-status
 *
 * 返回示例:
 * {
 *   "data": [{
 *     "id": "",
 *     "indexing_status": "indexing",
 *     "processing_started_at": 1681623462.0,
 *     "parsing_completed_at": 1681623462.0,
 *     "cleaning_completed_at": 1681623462.0,
 *     "splitting_completed_at": 1681623462.0,
 *     "completed_at": null,
 *     "paused_at": null,
 *     "error": null,
 *     "stopped_at": null,
 *     "completed_segments": 24,
 *     "total_segments": 100
 *   }]
 * }
 */
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, batch } = params;
        if (!datasetId || !batch) {
            return new Response(
                JSON.stringify({ error: '缺少必要参数 (datasetId, batch)' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

        console.log('[API] Indexing Status:', { datasetId, batch });

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