import fs from 'fs';
import path from 'path';
import { GoogleGenAI } from '@google/genai';

const GEMINI_API_KEY = (process.env.GEMINI_API_KEY || '').replace(/['"]/g, '').trim();

if (!GEMINI_API_KEY) {
    console.error('GEMINI_API_KEY is missing in .env file');
    process.exit(1);
}

const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
const MODEL = 'gemini-2.5-flash-lite';

console.log(`Gemini SDK initialized with ${MODEL}`);

const SLEEP_MS = 1000;
const MAX_RETRIES = 5;

async function sleep(ms: number) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}

async function callGemini(prompt: string): Promise<string> {
    for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
        try {
            const response = await ai.models.generateContent({
                model: MODEL,
                contents: prompt,
            });
            return (response.text || '').trim();
        } catch (error: any) {
            const msg = error.message || '';
            if ((msg.includes('429') || msg.includes('RESOURCE_EXHAUSTED') || msg.includes('503')) && attempt < MAX_RETRIES - 1) {
                const waitTime = Math.pow(2, attempt + 1) * 2000;
                console.log(`    ⏳ Rate limited, waiting ${waitTime / 2000}s... (attempt ${attempt + 1}/${MAX_RETRIES})`);
                await sleep(waitTime);
                continue;
            }
            throw error;
        }
    }
    throw new Error('Max retries exceeded');
}

async function translateText(text: string): Promise<string> {
    if (!text?.trim()) return '';
    return callGemini(`Translate the following text from Slovenian to English (US). Return ONLY the translated text, no explanations.\n\nText:\n${text}`);
}


async function translateJSON(postObject: any): Promise<any> {
    const jsonString = JSON.stringify(postObject, null, 2);

    const prompt = `Role: Professional translator and SEO expert.
Task: Translate this JSON object from Slovenian to English (US).
Instructions:
- Maintain identical JSON structure.
- Preserve HTML tags, but translate text and <img> alt attributes.
- Generate English slug from title.
- Add "paragraph" key for a 1-2 sentence SEO meta description.
- Return ONLY the raw JSON object. No markdown backticks, no explanations.

JSON to translate:
${jsonString}`;

    const rawResponse = await callGemini(prompt);

    try {
        // 1. Odstranimo morebitne backtick-e in besedo "json"
        let cleanedJson = rawResponse
            .replace(/```json/g, '')  // odstrani začetni ```json
            .replace(/```/g, '')      // odstrani končni ```
            .trim();                  // odstrani odvečne presledke

        // 2. Parsamo očiščen niz
        return JSON.parse(cleanedJson);
    } catch (e) {
        console.error("❌ Napaka pri branju JSON odgovora. Surov odgovor AI-ja:");
        console.log(rawResponse); // To ti bo pokazalo, kaj točno je AI poslal
        throw new Error(`JSON Parse error: ${e.message}`);
    }
}

async function run() {
    const sourcePath = path.resolve(process.cwd(), 'clean_posts.json');
    const targetPath = path.resolve(process.cwd(), 'clean_posts_en.json');

    const sourcePosts = JSON.parse(fs.readFileSync(sourcePath, 'utf8'));
    let targetPosts: any[] = [];

    if (fs.existsSync(targetPath)) {
        try {
            const content = fs.readFileSync(targetPath, 'utf8');
            if (content.trim() && content.trim() !== '[]') {
                targetPosts = JSON.parse(content);
            }
        } catch (e) {
            console.warn('Could not parse target file, starting fresh.');
        }
    }

    console.log(`Source: ${sourcePosts.length} posts | Already translated: ${targetPosts.length}`);

    let translated = 0, skipped = 0, failed = 0;

    for (let i = 0; i < sourcePosts.length; i++) {
        const post = sourcePosts[i];

        const exists = targetPosts.find((p: any) => p.slug === post.slug);
        if (exists && exists.title && exists.content_html && exists.paragraph) {
            skipped++;
            continue;
        }

        console.log(`[${i + 1}/${sourcePosts.length}] 🔄 ${post.title}`);

        try {

            // console.log(post);
            const translatedPostRaw = await translateJSON(JSON.stringify(post, null, 2));
            const translatedPost = translatedPostRaw;

            await sleep(SLEEP_MS);

            if (exists) {
                targetPosts[targetPosts.indexOf(exists)] = translatedPost;
            } else {
                targetPosts.push(translatedPost);
            }

            fs.writeFileSync(targetPath, JSON.stringify(targetPosts, null, 2), 'utf8');
            console.log(`    ✅ Saved`);
            translated++;

        } catch (error: any) {
            console.error(`    ❌ Failed: ${error.message?.substring(0, 200)}`);
            fs.writeFileSync(targetPath, JSON.stringify(targetPosts, null, 2), 'utf8');
            failed++;
            continue;
        }
    }

    console.log(`\n=== Done ===`);
    console.log(`Translated: ${translated} | Skipped: ${skipped} | Failed: ${failed}`);
    console.log(`Total in output: ${targetPosts.length}`);
}

run();
