const fs = require('fs');
const path = require('path');

const pagesDir = path.resolve(__dirname, 'resources/js/Pages');
const walkSync = (dir, filelist = []) => {
  fs.readdirSync(dir).forEach(file => {
    const dirFile = path.join(dir, file);
    if (fs.statSync(dirFile).isDirectory()) {
      filelist = walkSync(dirFile, filelist);
    } else {
      if (dirFile.endsWith('.vue')) {
        filelist.push(dirFile);
      }
    }
  });
  return filelist;
};

const files = walkSync(pagesDir).filter(f => !f.includes('/Fragments/') && !f.includes('/Core/'));

files.forEach(file => {
  let content = fs.readFileSync(file, 'utf8');
  const filename = path.basename(file, '.vue');
  
  let title = filename.replace(/([A-Z])/g, ' $1').trim();
  if (title === 'Login') title = 'Login';
  
  if (!content.includes('usePageTitle(')) {
    const importRegex = /<script\b[^>]*setup[^>]*>/i;
    const importMatch = content.match(importRegex);
    
    if (importMatch) {
      let depth = file.split('resources/js/Pages/')[1].split('/').length - 1;
      let relativePrefix = depth === 0 ? '../' : '../../'.repeat(depth);
      let relativePath = `${relativePrefix}composables/Core/usePageTitle`;
      
      let importStr = `\nimport { usePageTitle } from '${relativePath}';`;
      let hookStr = `\nusePageTitle('${title}');\n`;
      
      content = content.replace(importRegex, `${importMatch[0]}${importStr}${hookStr}`);
      fs.writeFileSync(file, content);
      console.log('Updated', file, 'with title', title);
    } else {
      console.log('No script setup found in', file);
    }
  } else {
    console.log('Skipped', file, '(already has usePageTitle)');
  }
});
