/**
 * Fix PageShell wrap issues: missing imports, broken </div> closers.
 */
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const pagesDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '../src/web/src/pages');
const files = fs.readdirSync(pagesDir).filter(f => f.endsWith('.js'));

for (const file of files) {
  const fp = path.join(pagesDir, file);
  let c = fs.readFileSync(fp, 'utf8');
  let changed = false;

  if (c.includes('<PageShell') && !c.includes("from '../components/sovereign'")) {
    const m = c.match(/^import .+;\n/m);
    if (m) {
      const idx = c.indexOf(m[0]) + m[0].length;
      c = `${c.slice(0, idx)}import { PageShell } from '../components/sovereign';\n${c.slice(idx)}`;
    } else {
      c = `import { PageShell } from '../components/sovereign';\n${c}`;
    }
    changed = true;
  }

  const broken = c.replace(/(<PageShell[^>]*>[\s\S]*?)<\/div>;/g, (match, open) => {
    if (open.includes('</PageShell>')) return match;
    changed = true;
    return `${open}</PageShell>;`;
  });
  c = broken;

  if (changed) {
    fs.writeFileSync(fp, c, 'utf8');
    console.log('fixed', file);
  }
}
