import { LocalAIService } from './localAi'
import { createStory, GeneratedStory, StoryVocabItem } from '@/lib/db'

export const SmartReadingService = {
    async generateStory(topic: string, difficulty: 'Easy' | 'Medium' | 'Hard'): Promise<string> {
        // 1. Construct Prompt
        const systemPrompt = `You are a Norwegian language teacher. 
Create a short story in Norwegian about "${topic}" for ${difficulty} level students.
Enclose 5-10 key vocabulary words in double curly braces like {{dette}} within the story content to create a fill-in-the-blank exercise.
You must return the result as a valid JSON object with the following structure:
{
  "title": "Story Title (in Norwegian)",
  "content": "The full story text in Norwegian with {{cloze}} words...",
  "vocab": [
    { "word": "cloze", "translation": "English Translation" },
    ... (Match the words in braces)
  ]
}
Do NOT include any text outside the JSON object.
Ensure the JSON is valid.`;

        const messages = [
            { role: "system", content: systemPrompt },
            { role: "user", content: `Generate a ${difficulty} story about ${topic}.` }
        ];

        // 2. Call AI
        // We need to ensure chat server is running? The UI usually handles this, 
        // but service should probably handle it or throw. 
        // LocalAIService doesn't auto-start yet. UI handles it.
        // We assume UI ensures server is ready.

        let content = await LocalAIService.chatCompletion(messages);

        // 3. Clean Response (sometimes models add markdown code blocks)
        content = content.trim();
        if (content.startsWith('```json')) {
            content = content.replace(/^```json\s*/, '').replace(/\s*```$/, '');
        } else if (content.startsWith('```')) {
            content = content.replace(/^```\s*/, '').replace(/\s*```$/, '');
        }

        // 4. Parse & Save
        try {
            const parsed = JSON.parse(content);
            const vocabList = parsed.vocab || [];
            // Deduplicate vocab
            const uniqueVocab = vocabList.filter((v: any, i: number, a: any[]) =>
                a.findIndex(t => t.word.toLowerCase() === v.word.toLowerCase()) === i
            );
            const vocabJson = JSON.stringify(uniqueVocab);

            const storyId = await createStory({
                title: parsed.title || "Untitled Story",
                content: parsed.content || "",
                difficulty: difficulty,
                topic: topic,
                vocab_json: vocabJson
            });

            return storyId;
        } catch (e) {
            console.error("Failed to parse AI response:", content);
            throw new Error("Failed to generate valid story JSON.");
        }
    }
}
