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

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);
        const { user } = await getSessionInfo(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('🚀 [API] Chat Messages API - 收到请求:', {
            user,
            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,
            user,
            responseMode,
            conversationId,
            files,
            frontendJWT  // 传递 JWT
        );

        console.log('📡 [API] Dify响应状态:', {
            status: response.status,
            statusText: response.statusText,
            hasBody: !!response.body,
            headers: Object.fromEntries(response.headers.entries())
        });

        // 对于流式响应，直接返回流
        if (responseMode === 'streaming') {
            console.log('🌊 [API] 返回流式响应');
            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
        console.log('📄 [API] 返回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',
                },
            }
        );
    }
} 