import "dotenv/config";
import { readFileSync, writeFileSync, existsSync } from "fs";
import { fileURLToPath } from "url";
import { dirname, join } from "path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Check if Zoom credentials are set
const ZOOM_ACCOUNT_ID = process.env.ZOOM_ACCOUNT_ID;
const ZOOM_CLIENT_ID = process.env.ZOOM_CLIENT_ID;
const ZOOM_CLIENT_SECRET = process.env.ZOOM_CLIENT_SECRET;
const ZOOM_HOST_USER_ID = process.env.ZOOM_HOST_USER_ID || "me";

console.log("\n🔍 Checking Zoom Credentials...\n");

if (ZOOM_ACCOUNT_ID && ZOOM_CLIENT_ID && ZOOM_CLIENT_SECRET) {
  console.log("✅ Zoom credentials are configured!");
  console.log(`   Account ID: ${ZOOM_ACCOUNT_ID.substring(0, 8)}...`);
  console.log(`   Client ID: ${ZOOM_CLIENT_ID.substring(0, 8)}...`);
  console.log(`   Client Secret: ${ZOOM_CLIENT_SECRET.substring(0, 8)}...`);
  console.log(`   Host User ID: ${ZOOM_HOST_USER_ID}\n`);
  process.exit(0);
} else {
  console.log("❌ Zoom credentials are NOT configured!\n");
  console.log("Missing variables:");
  if (!ZOOM_ACCOUNT_ID) console.log("   - ZOOM_ACCOUNT_ID");
  if (!ZOOM_CLIENT_ID) console.log("   - ZOOM_CLIENT_ID");
  if (!ZOOM_CLIENT_SECRET) console.log("   - ZOOM_CLIENT_SECRET");
  console.log("\n");

  // Try to find aibit_soft .env.local file
  const aibitSoftEnvPath = join(__dirname, "..", "aibit_soft", ".env.local");
  const aibitSoftEnvAltPath = join(__dirname, "..", "aibit_soft", ".env");
  
  let sourceEnvPath = null;
  if (existsSync(aibitSoftEnvPath)) {
    sourceEnvPath = aibitSoftEnvPath;
  } else if (existsSync(aibitSoftEnvAltPath)) {
    sourceEnvPath = aibitSoftEnvAltPath;
  }

  if (sourceEnvPath) {
    console.log(`📁 Found source .env file: ${sourceEnvPath}\n`);
    console.log("Attempting to copy Zoom credentials...\n");
    
    try {
      const sourceContent = readFileSync(sourceEnvPath, "utf-8");
      const lines = sourceContent.split("\n");
      
      const zoomVars = {};
      lines.forEach((line) => {
        const trimmed = line.trim();
        if (trimmed.startsWith("ZOOM_ACCOUNT_ID=")) {
          zoomVars.ZOOM_ACCOUNT_ID = trimmed.split("=")[1]?.trim();
        } else if (trimmed.startsWith("ZOOM_CLIENT_ID=")) {
          zoomVars.ZOOM_CLIENT_ID = trimmed.split("=")[1]?.trim();
        } else if (trimmed.startsWith("ZOOM_CLIENT_SECRET=")) {
          zoomVars.ZOOM_CLIENT_SECRET = trimmed.split("=")[1]?.trim();
        } else if (trimmed.startsWith("ZOOM_HOST_USER_ID=")) {
          zoomVars.ZOOM_HOST_USER_ID = trimmed.split("=")[1]?.trim() || "me";
        }
      });

      if (zoomVars.ZOOM_ACCOUNT_ID && zoomVars.ZOOM_CLIENT_ID && zoomVars.ZOOM_CLIENT_SECRET) {
        // Read or create Backend .env file
        const backendEnvPath = join(__dirname, ".env");
        let backendContent = "";
        
        if (existsSync(backendEnvPath)) {
          backendContent = readFileSync(backendEnvPath, "utf-8");
        }

        // Check if Zoom vars already exist
        const hasZoomVars = backendContent.includes("ZOOM_ACCOUNT_ID=") || 
                           backendContent.includes("ZOOM_CLIENT_ID=") || 
                           backendContent.includes("ZOOM_CLIENT_SECRET=");

        if (hasZoomVars) {
          // Update existing vars
          let updated = backendContent;
          updated = updated.replace(/ZOOM_ACCOUNT_ID=.*/g, `ZOOM_ACCOUNT_ID=${zoomVars.ZOOM_ACCOUNT_ID}`);
          updated = updated.replace(/ZOOM_CLIENT_ID=.*/g, `ZOOM_CLIENT_ID=${zoomVars.ZOOM_CLIENT_ID}`);
          updated = updated.replace(/ZOOM_CLIENT_SECRET=.*/g, `ZOOM_CLIENT_SECRET=${zoomVars.ZOOM_CLIENT_SECRET}`);
          updated = updated.replace(/ZOOM_HOST_USER_ID=.*/g, `ZOOM_HOST_USER_ID=${zoomVars.ZOOM_HOST_USER_ID || "me"}`);
          
          writeFileSync(backendEnvPath, updated, "utf-8");
          console.log("✅ Updated Zoom credentials in Backend/.env\n");
        } else {
          // Append new vars
          const zoomConfig = `\n# Zoom Meeting Integration\nZOOM_ACCOUNT_ID=${zoomVars.ZOOM_ACCOUNT_ID}\nZOOM_CLIENT_ID=${zoomVars.ZOOM_CLIENT_ID}\nZOOM_CLIENT_SECRET=${zoomVars.ZOOM_CLIENT_SECRET}\nZOOM_HOST_USER_ID=${zoomVars.ZOOM_HOST_USER_ID || "me"}\n`;
          writeFileSync(backendEnvPath, backendContent + zoomConfig, "utf-8");
          console.log("✅ Added Zoom credentials to Backend/.env\n");
        }
        
        console.log("🎉 Success! Zoom credentials have been copied.");
        console.log("   Please restart your backend server for changes to take effect.\n");
        process.exit(0);
      } else {
        console.log("⚠️  Could not find complete Zoom credentials in source file.");
        console.log("   Please manually copy them from aibit_soft/.env.local to Backend/.env\n");
        process.exit(1);
      }
    } catch (error) {
      console.error("❌ Error copying credentials:", error.message);
      console.log("\nPlease manually copy the Zoom credentials:\n");
      console.log("1. Open aibit_soft/.env.local");
      console.log("2. Find these lines:");
      console.log("   ZOOM_ACCOUNT_ID=...");
      console.log("   ZOOM_CLIENT_ID=...");
      console.log("   ZOOM_CLIENT_SECRET=...");
      console.log("   ZOOM_HOST_USER_ID=me");
      console.log("3. Copy them to Backend/.env\n");
      process.exit(1);
    }
  } else {
    console.log("📝 Manual Setup Required:\n");
    console.log("1. Open aibit_soft/.env.local (or .env)");
    console.log("2. Find these lines:");
    console.log("   ZOOM_ACCOUNT_ID=...");
    console.log("   ZOOM_CLIENT_ID=...");
    console.log("   ZOOM_CLIENT_SECRET=...");
    console.log("   ZOOM_HOST_USER_ID=me");
    console.log("3. Copy them to Backend/.env");
    console.log("4. Restart the backend server\n");
    process.exit(1);
  }
}

