import { v2 as cloudinary } from 'cloudinary';
import { promises as fs } from 'fs';
import path from 'path';
import dotenv from 'dotenv';

// Load environment variables from .env.local
dotenv.config({ path: '.env.local' });

cloudinary.config({
  cloud_name: process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME,
  api_key: process.env.NEXT_PUBLIC_CLOUDINARY_API_KEY,
  api_secret: process.env.NEXT_PUBLIC_CLOUDINARY_API_SECRET,
  secure: true,
});

async function* getFiles(dir) {
  const dirents = await fs.readdir(dir, { withFileTypes: true });
  for (const dirent of dirents) {
    const res = path.resolve(dir, dirent.name);
    if (dirent.isDirectory()) {
      yield* getFiles(res);
    } else {
      yield res;
    }
  }
}

const uploadEverything = async (sourceRoot) => {
  try {
    const results = [];
    const absoluteRoot = path.resolve(sourceRoot);

    console.log(`🚀 Starting recursive upload from: ${sourceRoot}\n`);

    for await (const filePath of getFiles(absoluteRoot)) {
      const relativePath = path.relative(absoluteRoot, filePath);
      const ext = path.extname(filePath).toLowerCase();
      
      if (['.jpg', '.jpeg', '.png', '.webp', '.svg'].includes(ext)) {
        // Calculate the folder path inside Cloudinary
        // It will be: ayrisapart/Daire 1/image.jpg
        const cloudinaryFolder = path.join('ayrisapart', path.dirname(relativePath)).replace(/\\/g, '/');
        const filename = path.basename(filePath, ext);

        console.log(`⬆️ Uploading: ${relativePath}...`);
        
        const result = await cloudinary.uploader.upload(filePath, {
          folder: cloudinaryFolder,
          public_id: filename,
          use_filename: true,
          unique_filename: false,
        });

        console.log(`✅ Success: ${result.secure_url}`);
        results.push({
          localPath: relativePath,
          url: result.secure_url,
          public_id: result.public_id
        });
      }
    }

    // Save final mapping
    await fs.writeFile(
      'cloudinary-assets.json', 
      JSON.stringify(results, null, 2)
    );

    console.log(`\n✨ GREAT SUCCESS! ${results.length} images uploaded.`);
    console.log(`📄 Mapping details saved to: cloudinary-assets.json`);
  } catch (error) {
    console.error('❌ Error during recursive upload:', error);
  }
};

const target = process.argv[2] || 'public/ayrisapart';
uploadEverything(target);
