import { db } from '@/lib/db/db';
import { LLMService } from './llm-service';
import { ProviderManagementService } from './provider-management-service';
import { useSessionStore } from '@/store/use-session';
import { v4 as uuidv4 } from 'uuid';

export class ChatService {
    static async createSession(): Promise<string> {
        const id = uuidv4();
        await db.sessions.add({
            id,
            title: 'New Session',
            createdAt: Date.now(),
            updatedAt: Date.now(),
            status: 'active'
        });
        return id;
    }

    static async sendMessage(content: string, sessionId: string) {
        const sessionActions = useSessionStore.getState().actions;

        // Use ProviderManagementService to get active provider settings
        const settings = ProviderManagementService.getActiveProviderSettings();

        if (!settings.apiKey) {
            throw new Error('AI Provider not configured');
        }

        // 1. Save User Message
        await db.chatLogs.add({
            id: uuidv4(),
            role: 'user',
            content,
            timestamp: Date.now(),
            sessionId
        });

        // 2. Set Status to Thinking
        sessionActions.setTeacherStatus('thinking');

        try {
            // 3. Fetch Context (History)
            const history = await db.chatLogs
                .where('sessionId')
                .equals(sessionId)
                .sortBy('timestamp');

            // 4. Call LLM using active provider settings
            const responseContent = await LLMService.generateResponse({
                apiKey: settings.apiKey,
                baseUrl: settings.baseUrl,
                model: settings.modelName,
                messages: history.map(h => ({ role: h.role, content: h.content }))
            });

            // 5. Save Assistant Message
            await db.chatLogs.add({
                id: uuidv4(),
                role: 'assistant',
                content: responseContent,
                timestamp: Date.now(),
                sessionId
            });

            // 6. Update Session Timestamp
            await db.sessions.update(sessionId, { updatedAt: Date.now() });

        } catch (error) {
            console.error('ChatService Error:', error);
            // Optionally save an error system message
        } finally {
            sessionActions.setTeacherStatus('idle');
        }
    }

    // --- Stubs for ChatStore compatibility ---

    static async saveMessage(message: any): Promise<any> {
        await db.chatLogs.add({
            ...message,
            id: message.id || uuidv4()
        });
        return message;
    }

    static async getHistory(sessionId?: string): Promise<any[]> {
        if (sessionId) {
            return await db.chatLogs.where('sessionId').equals(sessionId).sortBy('timestamp');
        }
        return await db.chatLogs.orderBy('timestamp').toArray();
    }

    static async generateGhostwriterDraftStream(
        messages: any[],
        intent: any,
        sessionId: string,
        callbacks: {
            onToken: (token: string) => void;
            onComplete: (draft: any) => void;
            onError: (error: any) => void;
        }
    ) {
        try {
            // Import dynamically to avoid circular dependencies if any
            const { generateGhostwriterPrompt } = await import('../lib/llm/prompt-engine');
            const { DraftService } = await import('../lib/db/draft-service');

            // Generate Prompt using the new engine
            const prompt = generateGhostwriterPrompt(messages, intent);

            // Get Settings
            const settings = ProviderManagementService.getActiveProviderSettings();
            if (!settings.apiKey) throw new Error("AI Provider not configured");

            // For MVP: Use non-streaming generateResponse since LLMService doesn't support streaming yet
            // But simulate streaming tokens for UI effect
            const fullResponse = await LLMService.generateResponse({
                apiKey: settings.apiKey,
                baseUrl: settings.baseUrl,
                model: settings.modelName,
                messages: [{ role: 'user', content: prompt }]
            });

            // Parse title (simple heuristic: first line # Title or just "Draft")
            let title = 'Ghostwriter Draft';
            const titleMatch = fullResponse.match(/^#\s+(.+)$/m);
            if (titleMatch) title = titleMatch[1].trim();

            const draftRecord = {
                sessionId,
                title,
                content: fullResponse,
                tags: [],
                createdAt: Date.now(),
                updatedAt: Date.now(),
                status: 'draft' as const
            };

            // Save to DB immediately so it's persisted (Story 3.1)
            const savedDraft = await DraftService.saveDraft(draftRecord);

            // Simulate streaming for UX
            const chunkSize = 10;
            for (let i = 0; i < fullResponse.length; i += chunkSize) {
                callbacks.onToken(fullResponse.slice(i, i + chunkSize));
                await new Promise(r => setTimeout(r, 10)); // Tiny delay
            }

            callbacks.onComplete(savedDraft);

        } catch (e) {
            console.error("Ghostwriter Generation Error:", e);
            callbacks.onError(e);
        }
    }

    static async startRefinement(draftId: number): Promise<any> {
        return { id: draftId, content: 'Original content' };
    }

    static async submitRefinementFeedback(feedback: string, originalDraft: any): Promise<any> {
        return { ...originalDraft, content: originalDraft.content + '\n\nRefined: ' + feedback };
    }

    static async approveDraft(draftId: number): Promise<void> {
        // Call DraftService
        const { DraftService } = await import('../lib/db/draft-service');
        await DraftService.markAsCompleted(draftId);
    }
}
