import { readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';

const repoRoot = process.cwd();
const publicSwPath = resolve(repoRoot, 'public', 'sw.js');
const distSwPath = resolve(repoRoot, 'dist', 'sw.js');
const distIndexHtmlPath = resolve(repoRoot, 'dist', 'index.html');
const radioConfigPath = resolve(repoRoot, 'src', 'radio', 'radioConfig.json');
const serviceWorkerConfigPath = resolve(repoRoot, 'src', 'shared', 'serviceWorkerConfig.json');

const distIndexHtml = await readFile(distIndexHtmlPath, 'utf8');
const buildStampMatch = distIndexHtml.match(/assets\/(?:main|player)-(\d+)-/);
if (!buildStampMatch) {
  throw new Error('Unable to infer build stamp from dist/index.html.');
}

const buildStamp = buildStampMatch[1];
const radioConfig = JSON.parse(await readFile(radioConfigPath, 'utf8'));
const serviceWorkerConfig = JSON.parse(await readFile(serviceWorkerConfigPath, 'utf8'));
const swTemplate = await readFile(publicSwPath, 'utf8');

const stampedSource = swTemplate
  .replaceAll('__APP_BUILD_ID__', buildStamp)
  .replace('__RADIO_COUNTRIES_JSON__', JSON.stringify(radioConfig.radioCountries))
  .replaceAll('__MANAGED_COUNTRY_CODE__', String(radioConfig.managedCountryCode ?? 'SI'))
  .replaceAll('__SW_STATION_SYNC_TAG__', serviceWorkerConfig.stationSyncTag)
  .replaceAll('__SW_STATION_PERIODIC_SYNC_TAG__', serviceWorkerConfig.stationPeriodicSyncTag)
  .replaceAll('__SW_MANAGED_CATALOG_PERIODIC_SYNC_TAG__', serviceWorkerConfig.managedCatalogPeriodicSyncTag)
  .replaceAll('__SW_STATION_SYNC_META_PATH__', serviceWorkerConfig.stationSyncMetaPath);

await writeFile(distSwPath, stampedSource, 'utf8');
console.log(`[stamp-dist-sw] Updated dist/sw.js with build stamp ${buildStamp}`);
