import { v2 as cloudinary } from 'cloudinary';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// Setup environment variables manually from .env.local
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const envPath = path.resolve(__dirname, '../.env.local');
const envContent = fs.readFileSync(envPath, 'utf8');

const env = {};
envContent.split('\n').forEach(line => {
  const [key, ...valueParts] = line.split('=');
  if (key && valueParts.length > 0) {
    let value = valueParts.join('=').trim();
    if (value.startsWith('"') && value.endsWith('"')) {
      value = value.substring(1, value.length - 1);
    }
    env[key] = value;
  }
});

cloudinary.config({
  cloud_name: env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME,
  api_key: env.CLOUDINARY_API_KEY,
  api_secret: env.CLOUDINARY_API_SECRET
});

const IMAGES_DIR = path.resolve(__dirname, '../public/images');

async function uploadFiles(dir) {
  const entries = fs.readdirSync(dir, { withFileTypes: true });

  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      await uploadFiles(fullPath);
    } else if (entry.isFile() && /\.(png|jpg|jpeg|webp)$/i.test(entry.name)) {
      const relativePath = path.relative(IMAGES_DIR, fullPath);
      const folder = path.join('aydogan', path.dirname(relativePath)).replace(/\\/g, '/');
      const publicId = path.basename(entry.name, path.extname(entry.name));

      console.log(`Uploading: ${relativePath} to folder: ${folder}`);
      try {
        const result = await cloudinary.uploader.upload(fullPath, {
          folder: folder,
          public_id: publicId,
          overwrite: true,
          resource_type: 'image'
        });
        console.log(`Successfully uploaded: ${result.secure_url}`);
      } catch (error) {
        console.error(`Failed to upload ${relativePath}:`, error.message);
      }
    }
  }
}

console.log('Starting upload to Cloudinary...');
uploadFiles(IMAGES_DIR)
  .then(() => console.log('Upload finished!'))
  .catch(err => console.error('Upload failed:', err));
