import 'dotenv/config';
import { Client, ID } from "node-appwrite";

/**
 * Appwrite Platform Setup Script
 * Automatically adds the production platform to Appwrite to fix CORS issues
 */

const requiredEnv = [
  "APPWRITE_ENDPOINT",
  "APPWRITE_PROJECT_ID",
  "APPWRITE_API_KEY",
];

for (const k of requiredEnv) {
  if (!process.env[k]) {
    console.error(`❌ Missing env var: ${k}`);
    process.exit(1);
  }
}

const client = new Client()
  .setEndpoint(process.env.APPWRITE_ENDPOINT)
  .setProject(process.env.APPWRITE_PROJECT_ID)
  .setKey(process.env.APPWRITE_API_KEY);

// Production platform configuration
const PRODUCTION_PLATFORM = {
  type: 'web',
  name: 'Production',
  hostname: 'emailsorter.webklar.com',
  origin: 'https://emailsorter.webklar.com',
};

// Development platform configuration (optional)
const DEVELOPMENT_PLATFORM = {
  type: 'web',
  name: 'Development',
  hostname: 'localhost',
  origin: 'http://localhost:5173',
};

async function setupPlatforms() {
  try {
    console.log('🔧 Setting up Appwrite platforms...\n');

    // Use the Management API endpoint directly
    const endpoint = process.env.APPWRITE_ENDPOINT.replace('/v1', '');
    const projectId = process.env.APPWRITE_PROJECT_ID;
    const apiKey = process.env.APPWRITE_API_KEY;

    // Try to list existing platforms using the REST API
    console.log('📋 Checking existing platforms...');
    let existingPlatforms = { platforms: [] };
    
    try {
      const listResponse = await fetch(`${endpoint}/v1/projects/${projectId}/platforms`, {
        method: 'GET',
        headers: {
          'X-Appwrite-Project': projectId,
          'X-Appwrite-Key': apiKey,
          'Content-Type': 'application/json',
        },
      });

      if (listResponse.ok) {
        existingPlatforms = await listResponse.json();
        console.log(`✓ Found ${existingPlatforms.platforms?.length || 0} existing platform(s)\n`);
      } else {
        console.warn(`⚠️  Could not list platforms (${listResponse.status}), will attempt to create anyway\n`);
      }
    } catch (err) {
      console.warn(`⚠️  Could not list platforms: ${err.message}, will attempt to create anyway\n`);
    }

    // Check if production platform already exists
    const productionExists = existingPlatforms.platforms?.some(
      (p) => p.type === 'web' && (p.hostname === PRODUCTION_PLATFORM.hostname || p.hostname === PRODUCTION_PLATFORM.origin)
    );

    if (productionExists) {
      console.log('✓ Production platform already exists');
    } else {
      console.log('➕ Creating production platform...');
      try {
        const createResponse = await fetch(`${endpoint}/v1/projects/${projectId}/platforms`, {
          method: 'POST',
          headers: {
            'X-Appwrite-Project': projectId,
            'X-Appwrite-Key': apiKey,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            type: PRODUCTION_PLATFORM.type,
            name: PRODUCTION_PLATFORM.name,
            hostname: PRODUCTION_PLATFORM.hostname,
          }),
        });

        if (!createResponse.ok) {
          const errorText = await createResponse.text();
          throw new Error(`HTTP ${createResponse.status}: ${errorText}`);
        }

        const createdPlatform = await createResponse.json();
        console.log(`✓ Production platform created: ${createdPlatform.name || PRODUCTION_PLATFORM.name} (${createdPlatform.hostname || PRODUCTION_PLATFORM.hostname})`);
      } catch (createError) {
        // If API doesn't work, provide manual instructions
        throw new Error(`API call failed: ${createError.message}. The Appwrite Management API may not be available via REST. Please use the manual method below.`);
      }
    }

    // Check if development platform already exists
    const developmentExists = existingPlatforms.platforms?.some(
      (p) => p.type === 'web' && (p.hostname === DEVELOPMENT_PLATFORM.hostname || p.hostname === 'localhost')
    );

    if (developmentExists) {
      console.log('✓ Development platform already exists');
    } else {
      console.log('➕ Creating development platform...');
      try {
        const createResponse = await fetch(`${endpoint}/v1/projects/${projectId}/platforms`, {
          method: 'POST',
          headers: {
            'X-Appwrite-Project': projectId,
            'X-Appwrite-Key': apiKey,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            type: DEVELOPMENT_PLATFORM.type,
            name: DEVELOPMENT_PLATFORM.name,
            hostname: DEVELOPMENT_PLATFORM.hostname,
          }),
        });

        if (!createResponse.ok) {
          const errorText = await createResponse.text();
          // Development platform is optional, so we don't fail if it can't be created
          console.warn(`⚠️  Could not create development platform: ${createResponse.status} ${errorText}`);
        } else {
          const createdPlatform = await createResponse.json();
          console.log(`✓ Development platform created: ${createdPlatform.name || DEVELOPMENT_PLATFORM.name} (${createdPlatform.hostname || DEVELOPMENT_PLATFORM.hostname})`);
        }
      } catch (createError) {
        console.warn(`⚠️  Could not create development platform: ${createError.message}`);
      }
    }

    console.log('\n✅ Platform setup completed!');
    console.log('\n📝 Note: It may take 1-2 minutes for CORS changes to take effect.');
    console.log('   Please wait a moment and then test your application.\n');

  } catch (error) {
    console.error('\n❌ Error setting up platforms:', error.message);
    
    // Check if it's a scope/permission error
    if (error.message.includes('missing scopes') || error.message.includes('platforms.write')) {
      console.error('\n⚠️  API Key Scope Problem:' -ForegroundColor Yellow);
      console.error('   Dein API Key hat nicht die erforderlichen Berechtigungen (Scopes).');
      console.error('\n💡 Lösung - API Key mit richtigen Scopes erstellen:');
      console.error(`   1. Gehe zu ${process.env.APPWRITE_ENDPOINT.replace('/v1', '')}`);
      console.error('   2. Logge dich ein und öffne dein Projekt');
      console.error('   3. Gehe zu Settings → API Credentials');
      console.error('   4. Erstelle einen NEUEN API Key mit folgenden Scopes:');
      console.error('      ✓ platforms.read');
      console.error('      ✓ platforms.write');
      console.error('   5. Aktualisiere APPWRITE_API_KEY in server/.env');
      console.error('   6. Führe dieses Script erneut aus: npm run setup:platform');
      console.error('\n   ODER verwende die manuelle Methode (siehe unten).\n');
    } else {
      console.error('\n💡 Alternative - Manuelle Methode:');
      console.error(`   1. Gehe zu ${process.env.APPWRITE_ENDPOINT.replace('/v1', '')}`);
      console.error('   2. Logge dich ein und öffne dein Projekt');
      console.error('   3. Gehe zu Settings → Platforms (oder "Web")');
      console.error('   4. Klicke auf "Add Platform" → "Web"');
      console.error('   5. Fülle aus:');
      console.error(`      - Name: ${PRODUCTION_PLATFORM.name}`);
      console.error(`      - Hostname: ${PRODUCTION_PLATFORM.hostname}`);
      console.error(`      - Origin: ${PRODUCTION_PLATFORM.origin} (falls gefragt)`);
      console.error('   6. Speichere und warte 1-2 Minuten');
      console.error('\n   Siehe docs/setup/APPWRITE_CORS_SETUP.md für Details.\n');
    }
    process.exit(1);
  }
}

setupPlatforms();
