const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

const buildDir = path.resolve(__dirname, '..', 'build');
const manifestPath = path.join(buildDir, 'manifest.json');

const dependencies = [
  'wp-element',
  'wp-i18n',
  'wp-api-fetch',
  'wp-data',
  'wp-hooks',
  'wp-components',
  'wp-block-editor',
  'wp-blocks',
  'wp-dom-ready',
  'react',
  'react-dom',
];

if (!fs.existsSync(manifestPath)) {
  console.error(`Missing manifest: ${manifestPath}`);
  process.exit(1);
}

const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));

for (const entry of Object.values(manifest)) {
  if (!entry || !entry.isEntry || !entry.file || !entry.file.endsWith('.js')) {
    continue;
  }

  const jsPath = path.join(buildDir, entry.file);
  if (!fs.existsSync(jsPath)) {
    continue;
  }

  const assetPath = jsPath.replace(/\.js$/, '.asset.php');
  const version = crypto
    .createHash('md5')
    .update(fs.readFileSync(jsPath))
    .digest('hex')
    .slice(0, 8);

  const php = `<?php return array(
  'dependencies' => array(${dependencies.map((dep) => `'${dep}'`).join(', ')}),
  'version' => '${version}'
);
`;

  fs.mkdirSync(path.dirname(assetPath), { recursive: true });
  fs.writeFileSync(assetPath, php, 'utf8');
  console.log(`Generated ${path.relative(buildDir, assetPath)}`);
}
