const fs = require("fs");
const fse = require("fs-extra");
const path = require("path");
const { execSync } = require('child_process');

console.log("Starting Electron build finalization...");

// Define paths
const distPath = path.join(__dirname, "..", "dist");
const electronDistPath = path.join(__dirname, "..", "dist-electron");
const wwwPath = path.join(electronDistPath, "www");
const builtIndexPath = path.join(distPath, "index.html");
const finalIndexPath = path.join(wwwPath, "index.html");

// Ensure target directory exists
if (!fs.existsSync(wwwPath)) {
  fs.mkdirSync(wwwPath, { recursive: true });
}

// Copy assets directory
const assetsSrc = path.join(distPath, "assets");
const assetsDest = path.join(wwwPath, "assets");
if (fs.existsSync(assetsSrc)) {
  fse.copySync(assetsSrc, assetsDest, { overwrite: true });
}

// Copy favicon.ico
const faviconSrc = path.join(distPath, "favicon.ico");
if (fs.existsSync(faviconSrc)) {
  fs.copyFileSync(faviconSrc, path.join(wwwPath, "favicon.ico"));
}

// Copy manifest.webmanifest
const manifestSrc = path.join(distPath, "manifest.webmanifest");
if (fs.existsSync(manifestSrc)) {
  fs.copyFileSync(manifestSrc, path.join(wwwPath, "manifest.webmanifest"));
}

// Load and modify index.html from Vite output
let indexContent = fs.readFileSync(builtIndexPath, "utf-8");

// Inject the window.process shim after the first <script> block
indexContent = indexContent.replace(
  /<script[^>]*type="module"[^>]*>/,
  match => `${match}\n  window.process = { env: { VITE_PLATFORM: 'electron' } };`
);

// Write the modified index.html to dist-electron/www
fs.writeFileSync(finalIndexPath, indexContent);

// Copy preload script to resources
const preloadSrc = path.join(electronDistPath, "preload.js");
const preloadDest = path.join(electronDistPath, "resources", "preload.js");

// Ensure resources directory exists
const resourcesDir = path.join(electronDistPath, "resources");
if (!fs.existsSync(resourcesDir)) {
  fs.mkdirSync(resourcesDir, { recursive: true });
}

if (fs.existsSync(preloadSrc)) {
  fs.copyFileSync(preloadSrc, preloadDest);
  console.log("Preload script copied to resources directory");
} else {
  console.error("Preload script not found at:", preloadSrc);
}

// Copy capacitor.config.json to dist-electron
try {
  console.log("Copying capacitor.config.json to dist-electron...");
  const configPath = path.join(process.cwd(), 'capacitor.config.json');
  const targetPath = path.join(process.cwd(), 'dist-electron', 'capacitor.config.json');
  
  if (!fs.existsSync(configPath)) {
    throw new Error('capacitor.config.json not found in project root');
  }
  
  fs.copyFileSync(configPath, targetPath);
  console.log("Successfully copied capacitor.config.json");
} catch (error) {
  console.error("Failed to copy capacitor.config.json:", error);
  throw error;
}

console.log("Electron index.html copied and patched for Electron context.");