import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import fs from 'fs';
import path from 'path';

// Parse .env manually
try {
  const envPath = path.resolve(process.cwd(), '.env');
  if (fs.existsSync(envPath)) {
    const envContent = fs.readFileSync(envPath, 'utf8');
    envContent.split('\n').forEach((line) => {
      const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
      if (match) {
        const key = match[1];
        let value = match[2] || '';
        if (value.length > 0 && value.startsWith('"') && value.endsWith('"')) {
          value = value.substring(1, value.length - 1);
        }
        process.env[key] = value.trim();
      }
    });
  }
} catch (e) {
  // ignore
}

const region = process.env.AWS_REGION || 'eu-central-1';
const accessKeyId = process.env.AWS_ACCESS_KEY_ID || '';
const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY || '';
const bucketName = process.env.S3_BUCKET_NAME || 'apkagermanschool';

async function testRegions() {
  const regionsToTest = ['us-east-1', 'eu-central-1', 'eu-west-1', 'ap-south-1', 'us-west-2'];
  
  for (const r of regionsToTest) {
    console.log(`\n--- TESTING REGION: ${r} ---`);
    const s3 = new S3Client({
      region: r,
      forcePathStyle: true,
      credentials: {
        accessKeyId: 'AKIAYWGKACVKBFHPAXMU',
        secretAccessKey: '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',
      },
    });

    try {
      await s3.send(
        new PutObjectCommand({
          Bucket: 'apkagermanschool',
          Key: `test-region-${r}-${Date.now()}.txt`,
          Body: Buffer.from('Region test payload'),
          ContentType: 'text/plain',
        })
      );
      console.log(`🎉 SUCCESS IN REGION: ${r}`);
      break;
    } catch (err: any) {
      console.error(`❌ REGION ${r} FAILED:`, err.message, err.name || '');
    }
  }
}

testRegions();
