import { readFileSync, writeFileSync } from 'fs';
import { resolve } from 'path';
import { fileURLToPath } from 'url';

const workspaceLink = 'workspaces:*';
const __dirname = fileURLToPath(new URL('.', import.meta.url));

// Update target package.json
const targetPath = resolve(__dirname, '../dist/out/package.json');
const targetPackage = JSON.parse(readFileSync(targetPath, 'utf8'));

// Process all cm- dependencies
Object.keys(targetPackage.dependencies).forEach((dependency) => {
  if (dependency.startsWith('cwap-cm-')) {
    // Read source version from the corresponding package
    const sourcePath = resolve(__dirname, `../../${dependency}/package.json`);
    try {
      const sourcePackage = JSON.parse(readFileSync(sourcePath, 'utf8'));
      const sourceVersion = sourcePackage.version;

      if (targetPackage.dependencies[dependency] === workspaceLink) {
        targetPackage.dependencies[dependency] = sourceVersion;
      } else {
        targetPackage.dependencies[dependency] = workspaceLink;
      }
    } catch (err) {
      console.warn(`Warning: Could not read package.json for ${dependency} at ${sourcePath}: ${err.message}`);
    }
  }
});

// Write back the updated package.json
writeFileSync(targetPath, JSON.stringify(targetPackage, null, 2));
