#!/usr/bin/env node "use strict";var e=require("fs"),n=require("path"),t=require("readline"),s=require("openai"),o=require("dotenv");const a=t.createInterface({input:process.stdin,output:process.stdout});function r(e){return new Promise((n=>a.question(e,n)))}o.config();const i=process.env.OPENAI_API_KEY,c=process.env.OPENAI_ORGANIZATION;i||(console.error("Error: OPENAI_API_KEY is required to use the OpenAI API"),process.exit(1));const l=new class{opeanai;constructor(e,n){this.opeanai=new s.OpenAI({apiKey:e,organization:n})}async translate(e,n){const t=e.trim().replace(/\s+/g," ");try{const e=await this.opeanai.chat.completions.create({model:"gpt-3.5-turbo-0125",messages:[{role:"system",content:"Translate texts accurately"},{role:"user",content:`Translate to ${n}: "${t}"`}],max_tokens:100});return console.log("OpenAI response:",e),console.log("response.choices:",e.choices),console.log("response.choices[0]?.message:",e.choices[0]?.message),e.choices[0]?.message?.content?.trim()||""}catch(e){console.error("Error translating text",e),process.exit(1)}}}(i,c);const[,,u]=process.argv;async function g(){try{const t=n.join(process.cwd(),"translation.config.js");e.existsSync(t)||(console.error("Error: translation.config.js not found."),process.exit(1));return(await import(t)).translationConfig}catch(e){console.error("Error loading configuration:",e.message),process.exit(1)}}"init"===u?async function(){console.log("Welcome to the Elevation Team Translation CLI!");let t=await r("Enter the base locale (en): ")||"en";const s=(await r("Enter target locales separated by space or comma (es): ")||"es").split(/[\s,]+/).filter((e=>e));if(0===s.length&&s.push(t),s.includes(t))return void console.log("Warning: The base language is also included in the target languages. Please select a different base language.");if(1===s.length&&s[0]===t)return void console.log("Warning: The target language is the same as the base language. Please select a different target language.");let o=await r("Enter the input directory when the baseFile is located (src/translations): ")||"src/translations",i=await r("Enter the output directory for generated translation files (src/translations): ")||"src/translations",c=await r("Enter the output format js or json (json): ")||"json";const l=n.join(process.cwd(),"translation.config.js");if(e.existsSync(l))return void console.log("Config file already exists at translation.config.js");const u=await r("Which AI provider do you want to use for translations? (openai): ")||"openai",g=`\nexport const translationConfig = {\n defaultLanguage: '${t}', // Base language for translations\n languages: ['${t}', ${s.map((e=>`'${e}'`)).join(", ")}], // Target languages for translations\n inputDir: '${o}', // Directory for the base translation files\n outputDir: '${i}', // Directory for the generated translation files\n format: '${c}', // Output format (e.g., json, js)\n aiProvider: '${u}', // AI provider for translations\n};\n\n`;e.writeFileSync(l,g),console.log("Config file created successfully at translation.config.js");const p=n.join(process.cwd(),"package.json");if(!e.existsSync(p))return void console.error("Error: package.json not found. Please ensure you are in a Node.js project.");const f=JSON.parse(e.readFileSync(p,"utf-8"));f.scripts=f.scripts||{},f.scripts["translation:watch"]?console.log('Script "translation:watch" already exists in package.json'):(f.scripts["translation:watch"]="et-translations watch",console.log('Script "translation:watch" added to package.json')),f.scripts["translation:run"]?console.log('Script "translation:run" already exists in package.json'):(f.scripts["translation:run"]="et-translations run",console.log('Script "translation:run" added to package.json')),e.writeFileSync(p,JSON.stringify(f,null,2)),a.close()}():"watch"===u?g().then((t=>async function(t){const{defaultLanguage:s,languages:o,inputDir:a,outputDir:r,format:i}=t,c=n.join(process.cwd(),a,`${s}.${i}`);e.existsSync(c)||(console.error(`Base file not found: ${c}`),process.exit(1)),e.watch(c,(async t=>{if("change"===t){console.log(`Changes detected in ${c}`);try{const t=JSON.parse(e.readFileSync(c,"utf-8"));for(const a of o){if(a===s)continue;const o=n.join(process.cwd(),r,`${a}.${i}`);let c={};e.existsSync(o)&&(c=JSON.parse(e.readFileSync(o,"utf-8")));const u=Object.entries(t).filter((([e,n])=>!c[e]||c[e]!==n)).map((([e,n])=>({key:e,value:n})));if(u.length>0){const n=await Promise.all(u.map((({value:e})=>l.translate(e,a)))),t={...c};u.forEach((({key:e},s)=>{t[e]=n[s]})),e.writeFileSync(o,JSON.stringify(t,null,2)),console.log(`Translation updated for ${a} at ${o}`)}}}catch(e){console.error(`Error processing translations: ${e.message}`)}}})),console.log(`Watching for changes in ${c}`)}(t))):"run"===u?g().then((t=>async function(t){const{defaultLanguage:s,languages:o,inputDir:a,outputDir:r,format:i}=t,c=n.join(process.cwd(),a,`${s}.${i}`);e.existsSync(c)||(console.error(`Base file not found: ${c}`),process.exit(1));try{const t=JSON.parse(e.readFileSync(c,"utf-8"));for(const a of o){if(a===s)continue;const o=n.join(process.cwd(),r,`${a}.${i}`);let c={};e.existsSync(o)&&(c=JSON.parse(e.readFileSync(o,"utf-8")));const u=Object.entries(t).filter((([e,n])=>!c[e]||c[e]!==n)).map((([e,n])=>({key:e,value:n})));if(u.length>0){const n=await Promise.all(u.map((({value:e})=>l.translate(e,a)))),t={...c};u.forEach((({key:e},s)=>{t[e]=n[s]})),e.writeFileSync(o,JSON.stringify(t,null,2)),console.log(`Translation updated for ${a} at ${o}`)}}}catch(e){console.error(`Error processing translations: ${e.message}`)}}(t))):(console.log('Unknown command. Use "init", "watch", or "run".'),process.exit(1));