import { FILENAME, TOKEN } from './constants';
import LocalazyApi from '@localazy/ts-api';
import { Key } from '@localazy/ts-api/dist/models/responses/keys-in-file';
import { get, set } from './utils';
import * as fs from 'fs';

const api = LocalazyApi({
    projectToken: TOKEN,
    baseUrl: 'https://api.localazy.com',
});

export async function getProjectId(): Promise<string> {
    const projects = await api.listProjects();
    return projects[0].id;
}

export async function getFileId(projectId: string): Promise<string> {
    const files = await api.listFiles({ projectId });
    return files.find(file => file.name === FILENAME)!.id;
}

export async function uploadLocal(projectId: string, lang: 'en' | 'de'): Promise<void> {
    const langFile = (await import(`./../../../apps/red-ui/src/assets/i18n/redact/${lang}.json`)).default;

    await api.import({
        projectId,
        files: [
            {
                name: FILENAME,
                content: { type: 'json', features: ['plural_icu', 'filter_untranslated'], [lang]: langFile },
            },
        ],
        deprecate: 'project',
    });
}

export async function downloadLanguage(projectId: string, fileId: string, lang: 'en' | 'de'): Promise<any> {
    const response = await api.getFileContents({ projectId, fileId, lang });
    return JSON.parse(await response.text());
}

export async function listKeys(projectId: string, fileId: string, lang: 'en' | 'de'): Promise<Key[]> {
    const response = await api.listKeysInFileForLanguage({ projectId, fileId, lang });
    console.log(`Downloaded ${response.keys.length} keys for ${lang} language`);
    return response.keys;
}

export async function updateLocalEn(keys: Key[]): Promise<void> {
    const enFile = (await import('./../../../apps/red-ui/src/assets/i18n/redact/en.json')).default;

    keys.forEach(({ key, value }) => {
        if (get(enFile, key) !== undefined) {
            set(enFile, key, value);
        }
    });

    await fs.promises.writeFile('./../../apps/red-ui/src/assets/i18n/redact/en.json', JSON.stringify(enFile, null, 2));
}

export async function updateLocalDe(projectId: string, fileId: string): Promise<void> {
    const deFile = await downloadLanguage(projectId, fileId, 'de');
    await fs.promises.writeFile('./../../apps/red-ui/src/assets/i18n/redact/de.json', JSON.stringify(deFile, null, 2));
}
