import * as esbuild from 'esbuild';
import { readdir, rename } from 'fs/promises';
import { join, dirname, basename, extname } from 'path';
import { NovadiUnplugin } from '@novadi/core/unplugin';

// Convert PascalCase to kebab-case
function toKebabCase(str) {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
}

// Recursively rename files to kebab-case
async function renameFiles(dir) {
  const entries = await readdir(dir, { withFileTypes: true });

  for (const entry of entries) {
    const fullPath = join(dir, entry.name);

    if (entry.isDirectory()) {
      await renameFiles(fullPath);
    } else if (entry.isFile() && extname(entry.name) === '.js') {
      const baseName = basename(entry.name, '.js');
      const kebabName = toKebabCase(baseName);

      if (baseName !== kebabName) {
        const newPath = join(dirname(fullPath), kebabName + '.js');
        await rename(fullPath, newPath);
      }
    }
  }
}

// Build with esbuild
async function build() {
  try {
    // Calendar standalone bundle (no DI)
    await esbuild.build({
      entryPoints: ['src/entry.ts'],
      bundle: true,
      outfile: 'wwwroot/js/calendar.js',
      format: 'esm',
      sourcemap: 'inline',
      target: 'es2020',
      minify: false,
      keepNames: true,
      platform: 'browser'
    });

    console.log('Calendar bundle created: wwwroot/js/calendar.js');

    // Demo bundle (with DI transformer for autowiring)
    await esbuild.build({
      entryPoints: ['src/demo/index.ts'],
      bundle: true,
      outfile: 'wwwroot/js/demo.js',
      format: 'esm',
      sourcemap: 'inline',
      target: 'es2020',
      minify: false,
      keepNames: true,
      platform: 'browser',
      plugins: [NovadiUnplugin.esbuild({ debug: false, enableAutowiring: true, performanceLogging: true })]
    });

    console.log('Demo bundle created: wwwroot/js/demo.js');

  } catch (error) {
    console.error('Build failed:', error);
    process.exit(1);
  }
}

build();
