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 {
        const { user } = await getSessionInfo(request);
        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
        });

        const response = await difyClient.createChatMessage(
            inputs,
            query,
            user,
            responseMode,
            conversationId,
            files
        );

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