import { GoogleSheets } from './google-sheets'
import { generateLanguageTypes } from './generate-language-types'
import { identOf } from './ident'
import fs from 'fs/promises'
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = join(__dirname, '../../..');

// Flatten the sheet's dotted i18n map to inlang's snake_case token catalog.
// `website.hero.title` → `website_hero_title`. Identical transform to the app
// scaffold's identOf, so generator output ↔ runtime lookup stay aligned.
const toInlangCatalog = (flat: Record<string, string>): Record<string, string> => {
  const out: Record<string, string> = {}
  for (const [key, value] of Object.entries(flat)) {
    out[identOf(key)] = value
  }
  return out
}

export const main = async () => {
    let creds: any
    if (process.env.GOOGLE_SHEETS_SERVICE_ACCOUNT) {
        creds = JSON.parse(process.env.GOOGLE_SHEETS_SERVICE_ACCOUNT)
    } else {
        throw new Error('GOOGLE_SHEETS_SERVICE_ACCOUNT must be set')
    }
    const googleSheets = new GoogleSheets({
        client_email: creds.client_email,
        private_key: creds.private_key,
    }, '18Ct1kIbxJQXr5LQ8vDGRQkKUmWliieewkDaMLct91XE')

    let success = false
    for (let i = 0; i < 3; i++) {
        try {
            await googleSheets.init()

            const languages = ['en', 'de', 'uk', 'fil', 'tr', 'bs', 'sq', 'vi', 'es', 'hi', 'ar']

            // Read existing en.json locale file and sync missing keys to sheet
            try {
                const enLocaleData = await fs.readFile(`${rootDir}/apps/website/locales/en.json`, 'utf-8')
                const enLocale = JSON.parse(enLocaleData)
                console.log('Syncing locale keys to Google Sheets...')
                await googleSheets.syncLocaleToSheet(enLocale, languages)
            } catch (error) {
                console.log('No existing locales/en.json found or error syncing:', error)
            }

            const i18n = await googleSheets.getI18n(languages)
            for (const lang of languages) {
                await fs.mkdir(`${rootDir}/apps/website/locales/`, { recursive: true })
                await fs.writeFile(`${rootDir}/apps/website/locales/${lang.toLowerCase()}.json`, JSON.stringify(i18n[lang], null, 2))
                console.log(`Wrote ${Object.keys(i18n[lang]).length} keys for ${lang}`)
            }

            const resultI18n = await googleSheets.getResultI18n(languages)
            for (const lang of Object.keys(resultI18n)) {
                for (const sheet of Object.keys(resultI18n[lang])) {
                    await fs.mkdir(`${rootDir}/packages/functions/locales/${lang.toLowerCase()}`, { recursive: true })
                    await fs.writeFile(`${rootDir}/packages/functions/locales/${lang.toLowerCase()}/${sheet}.json`, JSON.stringify(resultI18n[lang][sheet], null, 2))
                    console.log(`Wrote ${Object.keys(resultI18n[lang][sheet]).length} keys for ${lang}/${sheet}`)
                }
            }

            // Generate TypeScript type definitions
            await generateLanguageTypes(rootDir)

            success = true
            break
        } catch (e) {
            await new Promise(res => setTimeout(res, 5000))
            console.error('Error fetching or writing i18n data:', e)
        }
    }

    if (!success) {
        console.error('Failed to generate i18n files after 3 attempts')
        process.exit(1)
    }
}

main()
