import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const versions = Object.freeze({ jquery: '4.0.0', jqueryUi: '1.14.2' });

const files = [
  {
    source: 'node_modules/jquery/dist/jquery.min.js',
    destination: `public/vendor/jquery/jquery-${versions.jquery}.min.js`,
    marker: `jQuery v${versions.jquery}`
  },
  {
    source: 'node_modules/jquery/LICENSE.txt',
    destination: 'public/vendor/jquery/LICENSE.txt',
    marker: 'OpenJS Foundation'
  },
  {
    source: 'node_modules/jquery-ui/dist/jquery-ui.min.js',
    destination: `public/vendor/jquery-ui/jquery-ui-${versions.jqueryUi}.min.js`,
    marker: `jQuery UI - v${versions.jqueryUi}`
  },
  {
    source: 'node_modules/jquery-ui/dist/themes/base/jquery-ui.min.css',
    destination: `public/vendor/jquery-ui/jquery-ui-${versions.jqueryUi}.min.css`,
    marker: `jQuery UI - v${versions.jqueryUi}`
  },
  {
    source: 'node_modules/jquery-ui/LICENSE.txt',
    destination: 'public/vendor/jquery-ui/LICENSE.txt',
    marker: 'OpenJS Foundation'
  }
];

async function copyVerifiedFile(file) {
  const source = path.join(root, file.source);
  const destination = path.join(root, file.destination);
  const content = await fs.readFile(source);
  if (!content.toString('utf8', 0, Math.min(content.length, 4096)).includes(file.marker)) {
    throw new Error(`Unerwarteter Inhalt in ${file.source}`);
  }
  await fs.mkdir(path.dirname(destination), { recursive: true });
  await fs.writeFile(destination, content);
  console.log(`Vendor-Datei synchronisiert: ${file.destination}`);
}

for (const file of files) await copyVerifiedFile(file);

const sourceImages = path.join(root, 'node_modules/jquery-ui/dist/themes/base/images');
const destinationImages = path.join(root, 'public/vendor/jquery-ui/images');
await fs.rm(destinationImages, { recursive: true, force: true });
await fs.mkdir(destinationImages, { recursive: true });
for (const entry of await fs.readdir(sourceImages, { withFileTypes: true })) {
  if (!entry.isFile()) continue;
  await fs.copyFile(path.join(sourceImages, entry.name), path.join(destinationImages, entry.name));
}
console.log('jQuery-UI-Themebilder synchronisiert.');
