import { readFile, readdir, stat } from 'node:fs/promises';
import path from 'node:path';
import process from 'node:process';

const root = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..');
const apps = ['admin', 'dashboard', 'carplace'];
const errors = [];

async function walk(directory) {
  const files = [];
  for (const entry of await readdir(directory, { withFileTypes: true })) {
    if (['node_modules', '.next', '.turbo', 'dist'].includes(entry.name)) continue;
    const target = path.join(directory, entry.name);
    if (entry.isDirectory()) files.push(...(await walk(target)));
    else files.push(target);
  }
  return files;
}

for (const app of apps) {
  const tokenPath = path.join(root, app, 'src', 'styles', 'phase16-tokens.css');
  const globalsPath = path.join(root, app, 'src', 'app', 'globals.css');
  try {
    await stat(tokenPath);
  } catch {
    errors.push(`${app}: missing Phase 16 token file`);
  }
  const globals = await readFile(globalsPath, 'utf8');
  if (!globals.includes('phase16-tokens.css')) {
    errors.push(`${app}: globals.css does not import Phase 16 tokens`);
  }
}

for (const app of apps) {
  for (const file of await walk(path.join(root, app, 'src'))) {
    if (!/\.(ts|tsx|css|json)$/.test(file)) continue;
    const contents = await readFile(file, 'utf8');
    if (contents.includes('RentalDriveGo')) {
      errors.push(`${path.relative(root, file)}: retired RentalDriveGo brand remains`);
    }
  }
}

const adminLayout = await readFile(path.join(root, 'admin/src/app/dashboard/layout.tsx'), 'utf8');
for (const required of ['navigationOpen', 'aria-current', 'RentalDriveGo', 'bg-blue-700']) {
  if (!adminLayout.includes(required)) errors.push(`admin dashboard shell missing ${required}`);
}

if (errors.length) {
  console.error(errors.join('\n'));
  process.exit(1);
}

console.log('Phase 16 design migration checks passed.');
