// Chat request timeout: 5 minutes (image/video generation can take a long time)
const CHAT_TIMEOUT_MS = 5 * 60 * 1000;

export class ChatService {
    static async sendChatMessage(
        history: { role: 'user' | 'model', parts: { text: string }[] }[], 
        newMessage: string,
        options?: { 
            isThinkingMode?: boolean, 
            isStoryboard?: boolean, 
            isHelpMeWrite?: boolean,
            onChunk?: (text: string) => void
        }
    ): Promise<string> {
        // Create abort controller for timeout
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), CHAT_TIMEOUT_MS);
        
        try {
            const messages = history.map(h => ({
                role: h.role === 'model' ? 'assistant' : 'user',
                content: h.parts[0].text
            }));
            messages.push({ role: 'user', content: newMessage });

            const stream = !!options?.onChunk;

            const response = await fetch('/chat/completions', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    messages,
                    stream,
                }),
                signal: controller.signal,
            });

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.detail || `Chat error: ${response.status}`);
            }

            if (stream && response.body) {
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullText = "";

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    
                    const chunk = decoder.decode(value, { stream: true });
                    const lines = chunk.split('\n');
                    
                    for (const line of lines) {
                        const trimmed = line.trim();
                        if (!trimmed || trimmed === 'data: [DONE]') continue;
                        if (trimmed.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(trimmed.slice(6));
                                let content = data.choices?.[0]?.delta?.content;
                                
                                // Handle AgentScope/OpenAI format differences
                                if (Array.isArray(content)) {
                                    content = content
                                        .filter((c: any) => c.type === 'text')
                                        .map((c: any) => c.text)
                                        .join('');
                                }
                                
                                if (content) {
                                    fullText += content;
                                    options?.onChunk?.(content);
                                }
                            } catch (e) {
                                console.warn('Error parsing SSE:', e);
                            }
                        }
                    }
                }
                return fullText;
            } else {
                const data = await response.json();
                return data.choices[0].message.content;
            }
        } catch (error: any) {
            // Handle abort/timeout error
            if (error.name === 'AbortError') {
                throw new Error('请求超时，请稍后重试');
            }
            console.error('ChatService error:', error);
            throw error;
        } finally {
            clearTimeout(timeoutId);
        }
    }

    static async connectLiveSession(
        onAudioData: (base64: string) => void,
        onClose: () => void
    ): Promise<any> {
        // TODO: Connect to backend realtime service
        console.warn("Live session currently disabled during backend migration");
        return {
            sendRealtimeInput: (data: any) => {
                console.log("Ignored realtime input:", data);
            },
            close: () => onClose()
        };
    }
}
