const fs = require('fs');
const readline = require('readline');
const path = require('path');

const logPath = 'C:/Users/BS/.gemini/antigravity/brain/393257b2-e812-421c-92f7-099f2362049e/.system_generated/logs/transcript.jsonl';

function safeParse(val) {
    if (typeof val === 'string') {
        try { return JSON.parse(val); } catch(e) { return val; }
    }
    return val;
}

async function extract() {
    const fileStream = fs.createReadStream(logPath);
    const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity
    });

    let indexHtml = '';
    let snapshots = [];
    
    // To handle initial creation vs updates
    for await (const line of rl) {
        try {
            const entry = JSON.parse(line);
            if (entry.tool_calls) {
                for (const tool of entry.tool_calls) {
                    try {
                        const name = tool.name || (tool.function && tool.function.name);
                        let args = tool.args;
                        if (!args && tool.function && tool.function.arguments) {
                            args = JSON.parse(tool.function.arguments);
                        } else if (typeof args === 'string') {
                            args = JSON.parse(args);
                        }
                        if (!args) continue;

                        let targetFile = safeParse(args.TargetFile || args.target_file || '');
                        let codeContent = safeParse(args.CodeContent || args.code_content || '');
                        let targetContent = safeParse(args.TargetContent || args.target_content || '');
                        let replacementContent = safeParse(args.ReplacementContent || args.replacement_content || '');

                        if ((name === 'write_to_file' || name === 'default_api:write_to_file') && targetFile.endsWith('index.html')) {
                            indexHtml = codeContent;
                            snapshots.push({ time: entry.created_at, size: indexHtml.length, content: indexHtml });
                        }
                        
                        if ((name === 'replace_file_content' || name === 'default_api:replace_file_content') && targetFile.endsWith('index.html') && indexHtml) {
                            if (indexHtml.includes(targetContent)) {
                                indexHtml = indexHtml.replace(targetContent, replacementContent);
                                snapshots.push({ time: entry.created_at, size: indexHtml.length, content: indexHtml });
                            }
                        }
                        
                        if ((name === 'multi_replace_file_content' || name === 'default_api:multi_replace_file_content') && targetFile.endsWith('index.html') && indexHtml) {
                            let chunks = safeParse(args.ReplacementChunks || args.replacement_chunks || '[]');
                            let changed = false;
                            for (let chunk of chunks) {
                                let tc = safeParse(chunk.TargetContent || chunk.targetContent || '');
                                let rc = safeParse(chunk.ReplacementContent || chunk.replacementContent || '');
                                if (indexHtml.includes(tc)) {
                                    indexHtml = indexHtml.replace(tc, rc);
                                    changed = true;
                                }
                            }
                            if (changed) {
                                snapshots.push({ time: entry.created_at, size: indexHtml.length, content: indexHtml });
                            }
                        }
                    } catch(e) {}
                }
            }
        } catch (e) {}
    }

    if (!fs.existsSync('d:/برنامج مخازن/index_backups')) {
        fs.mkdirSync('d:/برنامج مخازن/index_backups');
    }

    // Keep only some key snapshots to avoid creating too many files
    // Let's grab the first one of each day, or last one of each day
    console.log("Total index.html snapshots found:", snapshots.length);
    for (let i=0; i<snapshots.length; i++) {
        // Output every snapshot > 100kb, or the last 20
        if (snapshots[i].size > 50000) {
            let filename = 'd:/برنامج مخازن/index_backups/index_' + snapshots[i].time.replace(/[:TZ-]/g, '_') + '.html';
            fs.writeFileSync(filename, snapshots[i].content, 'utf8');
        }
    }
    console.log('Extraction complete.');
}
extract();
