/**
 * Batch-wrap pages that still use raw <main> with PageShell.
 * Skips Login, ComplianceGap, and pages already using PageShell.
 */
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const pagesDir = path.join(__dirname, '../src/web/src/pages');

const SKIP = new Set(['LoginPage.js', 'ComplianceGapPage.js']);

/** Fallback titles from filename */
function titleFromFile(file) {
  return file
    .replace(/Page\.js$/, '')
    .replace(/([a-z])([A-Z])/g, '$1 $2')
    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');
}

function extractPageTitle(content) {
  const m = content.match(/<h2[^>]*className="[^"]*page-title[^"]*"[^>]*>([^<]+)<\/h2>/);
  if (m) return m[1].trim();
  const m2 = content.match(/<h1[^>]*className="[^"]*page-title[^"]*"[^>]*>([^<]+)<\/h1>/);
  return m2 ? m2[1].trim() : null;
}

function wrapFile(filePath) {
  const file = path.basename(filePath);
  if (SKIP.has(file)) return { file, status: 'skip-excluded' };

  let content = fs.readFileSync(filePath, 'utf8');
  if (content.includes('PageShell')) return { file, status: 'skip-has-shell' };
  if (!content.includes('<main') && !content.includes('className="page"')) {
    return { file, status: 'skip-no-main' };
  }

  const title = extractPageTitle(content) || titleFromFile(file);
  const escapedTitle = title.replace(/"/g, '\\"');

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

  content = content.replace(
    /<main className="main[^"]*">/g,
    `<PageShell title="${escapedTitle}">`
  );
  content = content.replace(
    /<main className='main[^']*'>/g,
    `<PageShell title="${escapedTitle}">`
  );
  content = content.replace(/<\/main>/g, '</PageShell>');

  // div.page wrapper (some older pages)
  content = content.replace(
    /<div className="page">/g,
    `<PageShell title="${escapedTitle}">`
  );
  if (content.includes('<PageShell')) {
    content = content.replace(/<\/div>\s*\);\s*\n\}/, '</PageShell>\n  );\n}');
  }

  // Remove duplicate page-title h2/h1 immediately after PageShell open
  content = content.replace(
    /(<PageShell title="[^"]*">)\s*\n?\s*<h[12][^>]*className="[^"]*page-title[^"]*"[^>]*>[^<]*<\/h[12]>\s*\n?/g,
    '$1\n'
  );

  fs.writeFileSync(filePath, content, 'utf8');
  return { file, status: 'wrapped', title };
}

const files = fs.readdirSync(pagesDir).filter(f => f.endsWith('.js'));
const results = files.map(f => wrapFile(path.join(pagesDir, f)));
const wrapped = results.filter(r => r.status === 'wrapped');
console.log(`Wrapped ${wrapped.length} pages:`);
wrapped.forEach(r => console.log(`  ${r.file} → "${r.title}"`));
console.log('Skipped:', results.filter(r => r.status.startsWith('skip')).length);
