const fs = require('fs');
const path = require('path');

const projectRoot = path.resolve(__dirname, '..');
const indexPath = path.join(projectRoot, 'frontend-web', 'index.html');

const oldTitle = '<title>Base44 APP</title>';
const newTitle = '<title>KROW</title>';

const oldFavicon = '<link rel="icon" type="image/svg+xml" href="https://base44.com/logo_v2.svg" />';
const newFavicon = '<link rel="icon" type="image/svg+xml" href="https://krow-workforce-dev-launchpad.web.app/favicon.svg" />';

try {
  let content = fs.readFileSync(indexPath, 'utf8');

  if (content.includes(oldTitle)) {
    content = content.replace(oldTitle, newTitle);
    console.log('✅ Successfully patched title in frontend-web/index.html.');
  } else if (content.includes(newTitle)) {
    console.log('ℹ️ index.html title is already patched. Skipping.');
  } else {
    console.error('❌ Patching index.html failed: Could not find the expected title tag.');
    process.exit(1);
  }

  if (content.includes(oldFavicon)) {
    content = content.replace(oldFavicon, newFavicon);
    console.log('✅ Successfully patched favicon in frontend-web/index.html.');
  } else if (content.includes(newFavicon)) {
    console.log('ℹ️ index.html favicon is already patched. Skipping.');
  } else {
    console.error('❌ Patching index.html failed: Could not find the expected favicon link.');
    process.exit(1);
  }

  fs.writeFileSync(indexPath, content, 'utf8');

} catch (error) {
  console.error('❌ An error occurred during patching index.html:', error);
  process.exit(1);
}
