import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

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

// Paths
const sourcePath = path.join(__dirname, "..", "aibit_soft", ".env.local");
const targetPath = path.join(__dirname, ".env");

console.log("🔍 Looking for Zoom and SMTP credentials...\n");

// Read source file
let sourceContent = "";
if (fs.existsSync(sourcePath)) {
  console.log(`✅ Found source file: ${sourcePath}`);
  sourceContent = fs.readFileSync(sourcePath, "utf8");
} else {
  console.error(`❌ Source file not found: ${sourcePath}`);
  console.error("\nPlease ensure the file exists at: aibit_soft/.env.local");
  process.exit(1);
}

// Extract Zoom credentials
const lines = sourceContent.split("\n");
const zoomCredentials = {
  ZOOM_ACCOUNT_ID: null,
  ZOOM_CLIENT_ID: null,
  ZOOM_CLIENT_SECRET: null,
  ZOOM_HOST_USER_ID: null,
};

// Extract SMTP credentials
const smtpCredentials = {
  SMTP_HOST: null,
  SMTP_PORT: null,
  SMTP_USER: null,
  SMTP_PASS: null,
  SMTP_SECURE: null,
  ADMIN_EMAIL: null,
  COMPANY_EMAIL: null,
};

lines.forEach((line) => {
  const trimmed = line.trim();
  if (trimmed && !trimmed.startsWith("#")) {
    const match = trimmed.match(/^(\w+)=(.*)$/);
    if (match) {
      const key = match[1];
      const value = match[2].replace(/^["']|["']$/g, ""); // Remove quotes
      if (key in zoomCredentials) {
        zoomCredentials[key] = value;
      }
      if (key in smtpCredentials) {
        smtpCredentials[key] = value;
      }
    }
  }
});

// Check if all required credentials are found
const required = ["ZOOM_ACCOUNT_ID", "ZOOM_CLIENT_ID", "ZOOM_CLIENT_SECRET"];
const missing = required.filter((key) => !zoomCredentials[key]);

if (missing.length > 0) {
  console.error(`❌ Missing required Zoom credentials: ${missing.join(", ")}`);
  console.error("\nPlease ensure these are set in aibit_soft/.env.local");
  process.exit(1);
}

console.log("✅ Found Zoom credentials:");
console.log(`   ZOOM_ACCOUNT_ID: ${zoomCredentials.ZOOM_ACCOUNT_ID ? "✓" : "✗"}`);
console.log(`   ZOOM_CLIENT_ID: ${zoomCredentials.ZOOM_CLIENT_ID ? "✓" : "✗"}`);
console.log(`   ZOOM_CLIENT_SECRET: ${zoomCredentials.ZOOM_CLIENT_SECRET ? "✓" : "✗"}`);
if (zoomCredentials.ZOOM_HOST_USER_ID) {
  console.log(`   ZOOM_HOST_USER_ID: ${zoomCredentials.ZOOM_HOST_USER_ID}`);
}

console.log("\n✅ Found SMTP credentials:");
console.log(`   SMTP_HOST: ${smtpCredentials.SMTP_HOST ? "✓" : "✗"}`);
console.log(`   SMTP_PORT: ${smtpCredentials.SMTP_PORT || "465 (default)"}`);
console.log(`   SMTP_USER: ${smtpCredentials.SMTP_USER ? "✓" : "✗"}`);
console.log(`   SMTP_PASS: ${smtpCredentials.SMTP_PASS ? "✓" : "✗"}`);
if (smtpCredentials.ADMIN_EMAIL) {
  console.log(`   ADMIN_EMAIL: ${smtpCredentials.ADMIN_EMAIL}`);
}
if (smtpCredentials.COMPANY_EMAIL) {
  console.log(`   COMPANY_EMAIL: ${smtpCredentials.COMPANY_EMAIL}`);
}

// Read existing .env file if it exists
let existingContent = "";
if (fs.existsSync(targetPath)) {
  console.log(`\n📄 Found existing .env file: ${targetPath}`);
  existingContent = fs.readFileSync(targetPath, "utf8");
} else {
  console.log(`\n📄 Creating new .env file: ${targetPath}`);
}

// Remove existing Zoom and SMTP credentials from existing content
const existingLines = existingContent.split("\n");
const filteredLines = existingLines.filter((line) => {
  const trimmed = line.trim();
  return (
    (!trimmed.startsWith("ZOOM_") && !trimmed.startsWith("SMTP_") && 
     !trimmed.startsWith("ADMIN_EMAIL") && !trimmed.startsWith("COMPANY_EMAIL")) ||
    trimmed.startsWith("#")
  );
});

// Add new Zoom credentials
const newZoomLines = [];
newZoomLines.push("\n# Zoom API Credentials (copied from aibit_soft/.env.local)");
if (zoomCredentials.ZOOM_ACCOUNT_ID) {
  newZoomLines.push(`ZOOM_ACCOUNT_ID=${zoomCredentials.ZOOM_ACCOUNT_ID}`);
}
if (zoomCredentials.ZOOM_CLIENT_ID) {
  newZoomLines.push(`ZOOM_CLIENT_ID=${zoomCredentials.ZOOM_CLIENT_ID}`);
}
if (zoomCredentials.ZOOM_CLIENT_SECRET) {
  newZoomLines.push(`ZOOM_CLIENT_SECRET=${zoomCredentials.ZOOM_CLIENT_SECRET}`);
}
if (zoomCredentials.ZOOM_HOST_USER_ID) {
  newZoomLines.push(`ZOOM_HOST_USER_ID=${zoomCredentials.ZOOM_HOST_USER_ID}`);
}

// Add new SMTP credentials
const newSmtpLines = [];
newSmtpLines.push("\n# SMTP Email Configuration (copied from aibit_soft/.env.local)");
if (smtpCredentials.SMTP_HOST) {
  newSmtpLines.push(`SMTP_HOST=${smtpCredentials.SMTP_HOST}`);
}
if (smtpCredentials.SMTP_PORT) {
  newSmtpLines.push(`SMTP_PORT=${smtpCredentials.SMTP_PORT}`);
} else {
  newSmtpLines.push(`SMTP_PORT=465`);
}
if (smtpCredentials.SMTP_USER) {
  newSmtpLines.push(`SMTP_USER=${smtpCredentials.SMTP_USER}`);
}
if (smtpCredentials.SMTP_PASS) {
  newSmtpLines.push(`SMTP_PASS=${smtpCredentials.SMTP_PASS}`);
}
if (smtpCredentials.SMTP_SECURE) {
  newSmtpLines.push(`SMTP_SECURE=${smtpCredentials.SMTP_SECURE}`);
}
if (smtpCredentials.ADMIN_EMAIL) {
  newSmtpLines.push(`ADMIN_EMAIL=${smtpCredentials.ADMIN_EMAIL}`);
}
if (smtpCredentials.COMPANY_EMAIL) {
  newSmtpLines.push(`COMPANY_EMAIL=${smtpCredentials.COMPANY_EMAIL}`);
}

// Combine content
const finalContent = [...filteredLines, ...newZoomLines, ...newSmtpLines].join("\n");

// Write to .env file
fs.writeFileSync(targetPath, finalContent, "utf8");

console.log("\n✅ Successfully copied Zoom and SMTP credentials to Backend/.env");
console.log("\n📝 Next steps:");
console.log("   1. Review the Backend/.env file to ensure all credentials are correct");
console.log("   2. Restart your backend server");
console.log("   3. Run 'npm run check-zoom' to verify the credentials are loaded correctly");
if (!smtpCredentials.SMTP_HOST || !smtpCredentials.SMTP_USER || !smtpCredentials.SMTP_PASS) {
  console.log("\n⚠️  Warning: SMTP credentials are missing. Email notifications will not be sent.");
  console.log("   Please ensure SMTP_HOST, SMTP_USER, and SMTP_PASS are set in aibit_soft/.env.local");
}

