#!/usr/bin/env node

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

console.log('🚀 Starting build process...');

// Clean dist directory
console.log('🧹 Cleaning dist directory...');
if (fs.existsSync('./dist')) {
  fs.rmSync('./dist', { recursive: true, force: true });
}

// Create dist directories
console.log('📁 Creating dist directories...');
fs.mkdirSync('./dist/esm', { recursive: true });
fs.mkdirSync('./dist/cjs', { recursive: true });
fs.mkdirSync('./dist/types', { recursive: true });


// Generate i18n/index.ts file dynamically
console.log('📝 Generating i18n/index.ts...');
const i18nIndexPath = './i18n/index.ts';
if (fs.existsSync('./i18n')) {
  const files = fs.readdirSync('./i18n');
  const languages = [];
  
  files.forEach(file => {
    // Only include .ts files, exclude index.ts and README.md
    if (file.endsWith('.ts') && file !== 'index.ts') {
      const language = file.replace('.ts', '');
      languages.push(language);
    }
  });
  
  // Sort languages alphabetically for consistent output
  languages.sort();
  
  if (languages.length > 0) {
    const exportStatements = languages.map(lang => `export * from './${lang}';`).join('\n');
    const i18nIndexContent = `// Export all i18n modules
${exportStatements}
`;
    
    fs.writeFileSync(i18nIndexPath, i18nIndexContent);
    console.log(`✅ i18n/index.ts generated successfully with ${languages.length} languages`);
  } else {
    console.log('⚠️  No language files found for i18n/index.ts generation');
  }
}

// Generate root index.ts file
console.log('📝 Generating root index.ts...');
const rootIndexPath = './index.ts';
const rootIndexContent = `// Re-export all i18n modules
export * from './i18n';
`;
fs.writeFileSync(rootIndexPath, rootIndexContent);
console.log('✅ Root index.ts generated successfully');

// Build ES modules (after index files are generated)
console.log('📦 Building ES modules...');
try {
  execSync('npx tsc --project tsconfig.json', { stdio: 'inherit' });
  console.log('✅ ES modules built successfully');
} catch (error) {
  console.error('❌ Failed to build ES modules:', error.message);
  process.exit(1);
}

// Build CommonJS modules (after index files are generated)
console.log('📦 Building CommonJS modules...');
try {
  execSync('npx tsc --project tsconfig.cjs.json', { stdio: 'inherit' });
  console.log('✅ CommonJS modules built successfully');
} catch (error) {
  console.error('❌ Failed to build CommonJS modules:', error.message);
  process.exit(1);
}

// Transform CommonJS i18n index file to use individual const declarations
console.log('🔄 Transforming CommonJS i18n index...');
const cjsIndexPath = './dist/cjs/i18n/index.js';
if (fs.existsSync(cjsIndexPath)) {
  // Dynamically read language files from i18n folder
  const i18nDir = './i18n';
  const languages = [];
  
  if (fs.existsSync(i18nDir)) {
    const files = fs.readdirSync(i18nDir);
    files.forEach(file => {
      // Only include .ts files, exclude index.ts and README.md
      if (file.endsWith('.ts') && file !== 'index.ts') {
        const language = file.replace('.ts', '');
        languages.push(language);
      }
    });
    
    // Sort languages alphabetically for consistent output
    languages.sort();
  }
  
  if (languages.length > 0) {
    const constDeclarations = languages.map(lang => `const ${lang} = require('./${lang}').default;`).join('\n');
    const exportsObject = `module.exports = {\n  ${languages.join(',\n  ')}\n};`;
    
    const newContent = `"use strict";
// CommonJS exports for i18n modules
${constDeclarations}

${exportsObject}
`;
    
    fs.writeFileSync(cjsIndexPath, newContent);
    console.log(`✅ CommonJS i18n index transformed successfully with ${languages.length} languages`);
  } else {
    console.log('⚠️  No language files found in i18n directory');
  }
} else {
  console.log('⚠️  CommonJS index file not found for transformation');
}

// Note: TypeScript compilation completed using dynamically generated index files
console.log('📋 TypeScript compilation completed - using dynamically generated index files');

console.log('🎉 Build completed successfully!');
console.log('📁 Output directories:');
console.log('   - ES modules: ./dist/esm/');
console.log('   - CommonJS: ./dist/cjs/');
console.log('   - Type definitions: ./dist/types/');
