import fs from 'fs'
import path from 'path'
import { app } from 'electron'
import { configService } from '../services/ConfigService'

class MainI18n {
    private locales: Record<string, any> = {}

    constructor() {
        this.loadLocales()
    }

    private loadLocales() {
        try {
            // In development, locales are in src/renderer/src/locales
            // In production, they should be in a resources folder
            const isDev = !app.isPackaged
            let localesPath = ''
            
            if (isDev) {
                localesPath = path.join(app.getAppPath(), 'src/renderer/src/locales')
            } else {
                // Adjust for production path
                localesPath = path.join(process.resourcesPath, 'locales')
            }

            if (fs.existsSync(localesPath)) {
                const files = fs.readdirSync(localesPath)
                files.forEach(file => {
                    if (file.endsWith('.json')) {
                        const lang = file.replace('.json', '')
                        const content = fs.readFileSync(path.join(localesPath, file), 'utf-8')
                        this.locales[lang] = JSON.parse(content)
                    }
                })
            }
        } catch (e) {
            console.error('Failed to load main locales:', e)
        }
    }

    t(key: string, variables?: Record<string, string>): string {
        const lang = configService.getSettings().language || 'tr'
        const parts = key.split('.')
        let result = this.locales[lang] || this.locales['en'] || {}

        for (const part of parts) {
            result = result?.[part]
            if (!result) break
        }

        if (typeof result !== 'string') return key

        if (variables) {
            Object.entries(variables).forEach(([k, v]) => {
                result = (result as string).replace(`{{${k}}}`, v)
            })
        }

        return result
    }
}

export const i18nMain = new MainI18n()
export const t = (key: string, variables?: Record<string, string>) => i18nMain.t(key, variables)
