import { readFileSync, writeFileSync } from 'node:fs';
import { resolve, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildReleaseManifest, MANIFEST_FILE } from './release-manifest-lib.mjs';

export function generateReleaseManifest(root) {
  const base = resolve(root);
  const pkg = JSON.parse(readFileSync(join(base, 'package.json'), 'utf8'));
  const update = JSON.parse(readFileSync(join(base, 'update-manifest.json'), 'utf8'));
  const manifest = buildReleaseManifest(base, {
    version: pkg.version,
    updaterVersion: update.updaterVersion || update.updater_version,
    removedFiles: Array.isArray(update.removedFiles) ? update.removedFiles : [],
  });
  writeFileSync(join(base, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
  return manifest;
}

const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
if (invokedPath === fileURLToPath(import.meta.url)) {
  const root = process.argv[2] || process.cwd();
  try {
    const manifest = generateReleaseManifest(root);
    console.log(`Release-Manifest erstellt: ${manifest.files.length} Dateien, ${manifest.removedFiles.length} explizite Löschungen.`);
  } catch (error) {
    console.error(`[FEHLER] Release-Manifest konnte nicht erstellt werden: ${error.message}`);
    process.exit(1);
  }
}
