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

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

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

/**
 * DELETE /api/dataset/datasets/:datasetId/documents/:documentId/segments/:segmentId - 删除分段
 * POST - 更新分段 (Dify用POST更新分段，可传enabled参数切换状态)
 * Dify API: DELETE/POST /datasets/{dataset_id}/documents/{document_id}/segments/{segment_id}
 */
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' } }
            );
        }

        const method = request.method;
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}`;

        if (method === 'DELETE') {
            console.log('[API] Delete Segment:', { datasetId, documentId, segmentId });

            const response = await fetch(apiUrl, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${frontendJWT}`,
                },
            });

            // Dify删除分段返回 204 No Content
            if (response.status === 204) {
                return new Response(
                    JSON.stringify({ result: 'success' }),
                    { status: 200, headers: { 'Content-Type': 'application/json' } }
                );
            }

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

        if (method === 'POST') {
            // POST 用于更新分段（包括启用/禁用）
            const body = await request.json();
            console.log('[API] Update Segment:', { datasetId, documentId, segmentId, body });

            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' },
            });
        }

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

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