import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';

export function planBrowserBundle(appRoot) {
  const lock = JSON.parse(fs.readFileSync(path.join(appRoot, 'package-lock.json'), 'utf8'));
  const packages = ['playwright', 'playwright-core'].map(name => {
    const root = path.join(appRoot, 'node_modules', name), meta = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
    const declaration = lock.packages['node_modules/' + name];
    if (meta.version !== '1.64.1' || declaration.version !== meta.version || !declaration.integrity) throw new Error('Portable browser packages must match locked Playwright 1.64.1.');
    if (!fs.existsSync(path.join(root, 'LICENSE'))) throw new Error('The browser package requires its original LICENSE.');
    return { name, version: meta.version, root, integrity: declaration.integrity };
  });
  return { version: '1.64.1', packages };
}
export function copyBrowserBundle(runtimeDirectory, plan) {
  const runtime = path.resolve(runtimeDirectory), output = path.join(runtime, 'node_modules'), packages = [];
  const copy = (root, destination, relative = '') => {
    const records = [];
    for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
      if (entry.isSymbolicLink()) throw new Error('Browser runtime input cannot be a link.');
      const file = path.join(relative, entry.name), target = path.resolve(destination, file);
      if (!target.startsWith(output + path.sep)) throw new Error('Browser bundle escaped the owned runtime.');
      if (entry.isDirectory()) { fs.mkdirSync(target, { recursive: true }); records.push(...copy(root, destination, file)); continue; }
      const bytes = fs.readFileSync(path.join(root, file)); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, bytes);
      records.push({ path: file.replaceAll('\\', '/'), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
    }
    return records;
  };
  for (const pkg of plan.packages) packages.push({ name: pkg.name, version: pkg.version, integrity: pkg.integrity,
    files: copy(pkg.root, path.join(output, pkg.name)) });
  const result = { schemaVersion: 1, kind: 'workbench-browser-runtime', playwrightVersion: plan.version, browser: 'local Microsoft Edge',
    scope: 'win32-x64 static build checks; browser executable remains the locally installed Edge', packages };
  fs.writeFileSync(path.join(runtime, 'BROWSER-RUNTIME.json'), JSON.stringify(result, null, 2) + '\n'); return result;
}
