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

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
});

async function listAllImages() {
  let allImages = [];
  let nextCursor = null;

  console.log('Fetching image list from Cloudinary...');

  do {
    const result = await cloudinary.api.resources({
      type: 'upload',
      prefix: 'aydogan/',
      max_results: 500,
      next_cursor: nextCursor
    });

    allImages = allImages.concat(result.resources.map(res => res.secure_url));
    nextCursor = result.next_cursor;
  } while (nextCursor);

  console.log(`Found ${allImages.length} images.`);
  
  // Format the output for data.ts
  const formattedList = allImages.map(url => `  "${url}",`).join('\n');
  const fileContent = `export const ALL_CLOUDINARY_IMAGES = [\n${formattedList}\n];`;
  
  fs.writeFileSync(path.resolve(__dirname, '../lib/gallery_data.ts'), fileContent);
  console.log('Gallery data saved to lib/gallery_data.ts');
}

listAllImages().catch(err => console.error(err));
