import { readFile, writeFile } from 'node:fs/promises';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';

const repositoryRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
const sourcePath = join(
  repositoryRoot,
  'src',
  'toolbox',
  'manifest.source.json'
);
const outputPath = join(repositoryRoot, 'public', 'toolbox-app.json');
const packagePath = join(repositoryRoot, 'package.json');
const checkOnly = process.argv.includes('--check');

const source = JSON.parse(await readFile(sourcePath, 'utf8'));
const packageJson = JSON.parse(await readFile(packagePath, 'utf8'));

if (source.version !== packageJson.version) {
  throw new Error(
    `Manifest version ${source.version} differs from package version ${packageJson.version}`
  );
}

if (
  source.source?.repository !== 'https://git.add-ideas.de/lotobo/av-tools' ||
  source.source?.license !== 'GPL-3.0-or-later'
) {
  throw new Error(
    'Manifest source must identify the canonical av-tools repository and GPL-3.0-or-later licence'
  );
}

const serialized = `${JSON.stringify(source, null, 2)}\n`;
if (checkOnly) {
  const current = await readFile(outputPath, 'utf8').catch(() => '');
  if (current !== serialized) {
    throw new Error(
      `${relative(repositoryRoot, outputPath)} is stale; run npm run manifest:generate`
    );
  }
  console.log('Toolbox manifest is synchronized with its canonical source');
} else {
  await writeFile(outputPath, serialized);
  console.log(`Generated ${relative(repositoryRoot, outputPath)}`);
}
