import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Setup environment variables manually from .env
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const envPath = path.resolve(__dirname, '../.env');
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;
  }
});

const IMAGES_DIR = path.resolve(__dirname, '../public/images');
const OPENINARY_API_URL = env.OPENINARY_API_URL || 'https://media.ayris.tech';
const OPENINARY_API_KEY = env.OPENINARY_API_KEY;

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 filename = path.basename(entry.name);

      console.log(`Uploading: ${relativePath} to folder: ${folder}`);
      
      const buffer = fs.readFileSync(fullPath);
      const ext = path.extname(entry.name).toLowerCase().slice(1);
      const mime = ext === 'jpg' ? 'jpeg' : ext;
      const blob = new Blob([buffer], { type: `image/${mime}` });

      const formData = new FormData();
      formData.append("files", blob, filename);
      formData.append("folder", folder);

      try {
        const uploadRes = await fetch(`${OPENINARY_API_URL}/api/upload`, {
            method: "POST",
            headers: { 
                Authorization: `Bearer ${OPENINARY_API_KEY}` 
            },
            body: formData,
        });

        if (!uploadRes.ok) {
            const errorText = await uploadRes.text();
            console.error(`Failed to upload ${relativePath}:`, errorText);
        } else {
            const data = await uploadRes.json();
            console.log(`Successfully uploaded: ${data.files[0].url}`);
        }
        
        // Wait 1 second to respect rate limits (max 100 requests / 60 seconds = ~1.6 req/s max)
        await new Promise(resolve => setTimeout(resolve, 1000));
        
      } catch (error) {
        console.error(`Error uploading ${relativePath}:`, error.message);
      }
    }
  }
}

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