import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function syncModelsWithWS() {
  const sourceDir = path.resolve(__dirname, 'src/database/schemas');
  const targetDir = path.resolve(__dirname, '../farmcontrol-ws/src/database/schemas');

  console.log(`Syncing schemas from ${sourceDir} to ${targetDir}...`);

  try {
    await syncDirectory(sourceDir, targetDir, sourceDir);
    console.log('✅ Schema sync completed successfully!');
  } catch (error) {
    console.error('❌ Error syncing schemas:', error);
    process.exit(1);
  }
}

async function syncDirectory(source, target, rootSource) {
  // Create target directory if it doesn't exist
  try {
    await fs.access(target);
  } catch {
    await fs.mkdir(target, { recursive: true });
  }

  // Read all items in source directory
  const items = await fs.readdir(source, { withFileTypes: true });

  for (const item of items) {
    const sourcePath = path.join(source, item.name);
    const targetPath = path.join(target, item.name);

    if (item.isDirectory()) {
      // Recursively sync subdirectories
      await syncDirectory(sourcePath, targetPath, rootSource);
    } else if (item.isFile()) {
      // Copy file from source to target
      await fs.copyFile(sourcePath, targetPath);
      console.log(`  ✓ Copied: ${path.relative(rootSource, sourcePath)}`);
    }
  }
}

// Run the sync function when executed directly
syncModelsWithWS();

export { syncModelsWithWS };
