// scripts/sync-version.ts
const denoConfig = JSON.parse(await Deno.readTextFile("deno.json"));
const version = denoConfig.version;

console.log(`Syncing version ${version} across project files...`);

const filesToUpdate = [
  {
    path: "icalendar.ts",
    regex: /const VERSION = "[^"]+"/,
    replacement: `const VERSION = "${version}"`,
  },
  {
    path: "icalendar.plug.yaml",
    regex: /^version: .*/m,
    replacement: `version: ${version}`,
  },
  {
    path: "PLUG.md",
    regex: /version: .*/, 
    replacement: `version: "${version}"`,
  },
];

for (const file of filesToUpdate) {
  try {
    let content = await Deno.readTextFile(file.path);
    if (!content.match(file.regex)) {
        // If PLUG.md doesn't have version:, add it after the name: line
        if (file.path === "PLUG.md") {
            content = content.replace(/^name: .*/m, (match) => `${match}
version: "${version}"`);
        } else {
            console.warn(`⚠️ Could not find regex in ${file.path}, skipping.`);
            continue;
        }
    } else {
        content = content.replace(file.regex, file.replacement);
    }
    await Deno.writeTextFile(file.path, content);
    console.log(`✅ Updated ${file.path}`);
  } catch (e) {
    console.error(`❌ Could not update ${file.path}: ${e.message}`);
  }
}
