#!/usr/bin/env node
const fs = require("fs");
const path = require("path");

const currentDir = process.env.INIT_CWD || __dirname;
const appName = currentDir.split(path.sep).pop();

if (!appName) {
  console.error("❌ No app name detected. Using default 'MyApp'.");
  process.exit(1);
}

const replaceInFile = (filePath) => {
  const fullPath = path.join(__dirname, "..", filePath);
  if (fs.existsSync(fullPath)) {
    let content = fs.readFileSync(fullPath, "utf8");
    content = content
      .replace(/MyAwesomeApp/g, appName)
      .replace(/devminds/g, appName)
      .replace(/meTube/g, appName)
      .replace(/com\.devminds/g, `com.${appName.replace(/\s+/g, "").toLowerCase()}`)
      .replace(/com\.meTube/g, `com.${appName.replace(/\s+/g, "").toLowerCase()}`);
    fs.writeFileSync(fullPath, content, "utf8");
  }
};

const filesToReplace = [
  "template/package.json",
  "template/app.json",
  "template/android/app/src/main/AndroidManifest.xml",
  "template/android/app/src/main/java/com/meTube/MainActivity.java",
  "template/android/app/src/main/java/com/meTube/MainApplication.java",
  "template/ios/meTube.xcodeproj/project.pbxproj",
  "template/ios/meTube/Info.plist",
];

filesToReplace.forEach(replaceInFile);

// Rename iOS folder & project
const renameFolder = (oldName, newName) => {
  const oldPath = path.join(__dirname, "..", "template", "ios", oldName);
  const newPath = path.join(__dirname, "..", "template", "ios", newName);
  if (fs.existsSync(oldPath)) {
    fs.renameSync(oldPath, newPath);
  }
};

renameFolder("Devminds", appName);
renameFolder("meTube.xcodeproj", `${appName}.xcodeproj`);
renameFolder("meTube.xcworkspace", `${appName}.xcworkspace`);

console.log(`✅ Project renamed to "${appName}" successfully! 🚀`);
