import { type ActionFunctionArgs, type LoaderFunctionArgs } from '@remix-run/node';
import { difyClient } from '~/api/dify/client.server';
import { getSessionInfo } from '../utils/session.server';

/**
 * GET /api/chat-messages - 获取会话消息列表
 */
export async function loader({ request }: LoaderFunctionArgs) {
    try {
        // 获取用户会话信息和 JWT
        const { getUserSession } = await import("~/api/login/auth.server");
        const { frontendJWT } = await getUserSession(request);

        // 检查 JWT 是否存在
        if (!frontendJWT) {
            console.error('❌ [API] Chat Messages GET - JWT不存在');
            return new Response(
                JSON.stringify({ error: 'JWT认证失败，请重新登录' }),
                {
                    status: 401,
                    headers: { 'Content-Type': 'application/json' },
                }
            );
        }

        // 从 URL 参数获取 conversation_id
        const url = new URL(request.url);
        const conversationId = url.searchParams.get('conversation_id');

        if (!conversationId) {
            return new Response(
                JSON.stringify({ error: '缺少 conversation_id 参数' }),
                {
                    status: 400,
                    headers: { 'Content-Type': 'application/json' },
                }
            );
        }

        console.log('客戶端調用remix路由_Chat Messages GET - 获取消息列表:', { conversationId });

        const result = await difyClient.getConversationMessages(conversationId, frontendJWT);

        return new Response(JSON.stringify(result), {
            status: 200,
            headers: { 'Content-Type': 'application/json' },
        });

    } catch (error: any) {
        console.error('❌ [API] Chat Messages GET - Error:', error.message);
        const status = error.message?.includes('JWT认证失败') ? 401 : 500;
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to get messages' }),
            {
                status,
                headers: { 'Content-Type': 'application/json' },
            }
        );
    }
}

/**
 * POST /api/chat-messages - 发送聊天消息
 */
export async function action({ request }: ActionFunctionArgs) {
    if (request.method !== 'POST') {
        return new Response('Method not allowed', { status: 405 });
    }

    try {
        // 获取用户会话信息和 JWT
        const { getUserSession } = await import("~/api/login/auth.server");
        const { frontendJWT } = await getUserSession(request);

        // 检查 JWT 是否存在
        if (!frontendJWT) {
            console.error('❌ [API] Chat Messages API - JWT不存在');
            return new Response(
                JSON.stringify({ error: 'JWT认证失败，请重新登录' }),
                {
                    status: 401,
                    headers: { 'Content-Type': 'application/json' },
                }
            );
        }

        const body = await request.json();

        const {
            inputs,
            query,
            files,
            conversation_id: conversationId,
            response_mode: responseMode,
        } = body;

        console.log('客戶端調用remix路由_Chat Messages API - 收到请求:', {
            queryLength: query?.length || 0,
            queryPreview: query?.substring(0, 100) + (query?.length > 100 ? '...' : ''),
            conversationId,
            responseMode,
            hasInputs: !!inputs,
            hasFiles: !!files && files.length > 0,
            filesCount: files?.length || 0,
            hasJWT: !!frontendJWT
        });

        const response = await difyClient.createChatMessage(
            inputs,
            query,
            responseMode,
            conversationId,
            files,
            frontendJWT  // 传递 JWT
        );

        // 对于流式响应，直接返回流
        if (responseMode === 'streaming') {
            console.log('Dify转发fastapi,返回流式响应');
            return new Response(response.body, {
                status: response.status,
                headers: {
                    'Content-Type': 'text/event-stream',
                    'Cache-Control': 'no-cache',
                    'Connection': 'keep-alive',
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'POST',
                    'Access-Control-Allow-Headers': 'Content-Type',
                },
            });
        }

        // 对于非流式响应，返回JSON
        return new Response(JSON.stringify(response), {
            status: 200,
            headers: {
                'Content-Type': 'application/json',
            },
        });

    } catch (error: any) {
        console.error('❌ [API] Chat Messages API - Error:', {
            message: error.message,
            stack: error.stack,
            name: error.name
        });

        // 检查是否是JWT认证失败
        const status = error.message?.includes('JWT认证失败') ? 401 : 500;

        return new Response(
            JSON.stringify({ error: error.message || 'Failed to send message' }),
            {
                status,
                headers: {
                    'Content-Type': 'application/json',
                },
            }
        );
    }
} 