/**
 * Wrap tailwind-style pages (div.p-6) that lack 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']);

function extractTitle(content) {
  const h1 = content.match(/<h1[^>]*>([^<]+)<\/h1>/);
  if (h1) return h1[1].replace(/&amp;/g, '&').trim();
  return null;
}

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

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

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

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

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

  // Wrap outer return div.p-6
  content = content.replace(
    /return \(\s*\n(\s*)<div className="p-6([^"]*)">/,
    `return (\n$1<PageShell title="${escapedTitle}">\n$1<div className="p-6$2">`
  );

  // Close PageShell before final return closing paren
  const lastReturnClose = content.lastIndexOf('\n  );');
  if (lastReturnClose > -1 && content.includes('<PageShell')) {
    content = `${content.slice(0, lastReturnClose)}\n    </PageShell>${content.slice(lastReturnClose)}`;
  }

  // Remove duplicate h1 if immediately after opening div
  content = content.replace(
    /(<div className="p-6[^"]*">\s*\n\s*)<h1[^>]*>[^<]*<\/h1>\s*\n/,
    '$1'
  );

  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 => wrapTailwind(path.join(pagesDir, f)));
console.log('Tailwind wrap:', results.filter(r => r.status === 'wrapped'));
