import fs from 'fs'
import path from 'path'

function generateExportedPrompt(literal: any): string {
    // First, let's check if literal and its required properties exist
    if (!literal) {
        return '';
    }

    // Create sections array with basic content
    const sections = [
        literal.introText || '',
        `استراتژی‌های گفتگو:\n${literal.strategiesText || ''}`,
        `قوانین گفتگو:\n${literal.rulesText || ''}`
    ];
    
    // Process companies list only if it exists and we're in prop_firms mode
    if (process.env.NEXT_PUBLIC_PANEL_TEMPLATE === 'prop_firms' && literal.companies && Array.isArray(literal.companies)) {
        const companyList = literal.companies.map((company: any) =>
            `${company.name} (${company.popularity}, ${company.description})`
        ).join(', ');
        
        // Only add to sections if companyRankingPrompt exists
        if (literal.companyRankingPrompt) {
            sections.push(literal.companyRankingPrompt.replace("{لیست_شرکت_ها_و_مقدار_محبوبیت}", companyList));
        }
    }
    
    // Process commands only if they exist
    if (literal.commands && Array.isArray(literal.commands)) {
        const commandsList = literal.commands.map((cmd: any) =>
            `- ${cmd.command}: پرامپت: ${cmd.prompt}`
        ).join('\n');
        
        sections.push(`دستورات لیترال:\n${commandsList}`);
    }
    
    // Add templateText if it exists
    if (literal.templateText) {
        sections.push(literal.templateText);
    }
    
    return sections.filter(section => section).join('\n\n');
}

export async function seedLiterals(prisma: any) {
    try {
        let literalsDataRaw = null;
        let filePath = '';
        
        if (process.env.NEXT_PUBLIC_PANEL_TEMPLATE === 'prop_firms') {
            filePath = path.join(__dirname, '/content/prop_firms/literalSeed.json');
        } else if (process.env.NEXT_PUBLIC_PANEL_TEMPLATE === 'general') {
            filePath = path.join(__dirname, '/content/general/literalSeed.json');
        }
        
        // Check if file exists before reading
        if (filePath && fs.existsSync(filePath)) {
            literalsDataRaw = fs.readFileSync(filePath, 'utf8');
        } else {
            console.log(`File not found: ${filePath}`);
            return;
        }
        
        if (literalsDataRaw) {
            const literalsData = JSON.parse(literalsDataRaw);
            
            for (const literal of literalsData) {
                const generatedFinalPrompt = generateExportedPrompt(literal);
                
                await prisma.literals.create({
                    data: {
                        id: literal.id,
                        finalPrompt: generatedFinalPrompt,
                        commands: literal.commands || [],
                        companies: literal.companies || [],
                        introText: literal.introText || '',
                        strategiesText: literal.strategiesText || '',
                        rulesText: literal.rulesText || '',
                        templateText: literal.templateText || '',
                        welcomeText: literal.welcomeText || '',
                        skillPrompt: literal.skillPrompt || '',
                        enthusiasmPrompt: literal.enthusiasmPrompt || '',
                        customerPrompt: literal.customerPrompt || '',
                        companyRankingPrompt: literal.companyRankingPrompt || '',
                        createdAt: new Date(literal.createdAt || new Date())
                    }
                });
            }
        }
    } catch (error) {
        console.error('Error in seedLiterals:', error);
        throw error;
    }
}