import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// Replicate __dirname functionality in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const projectRoot = path.join(__dirname, '..', 'frontend-web');

// --- Patching Functions ---

function applyPatch(filePath, patchInfo) {
  const fullPath = path.join(projectRoot, filePath);
  if (!fs.existsSync(fullPath)) {
    console.warn(`🟡 File not found, patch skipped: ${filePath}`);
    return;
  }

  let content = fs.readFileSync(fullPath, 'utf8');
  
  if (patchInfo.new_string && content.includes(patchInfo.new_string)) {
    console.log(`✅ Patch already applied in ${filePath}.`);
    return;
  }
  
  if (patchInfo.old_string && content.includes(patchInfo.old_string)) {
    content = content.replace(patchInfo.old_string, patchInfo.new_string);
    fs.writeFileSync(fullPath, content, 'utf8');
    console.log(`🟢 Patch applied in ${filePath}.`);
  } else {
    console.error(`🔴 Could not apply patch in ${filePath}. String not found.`);
  }
}

// --- Global Import Fix ---

function fixAllComponentImports(directory) {
  const entries = fs.readdirSync(directory, { withFileTypes: true });

  for (const entry of entries) {
    const fullPath = path.join(directory, entry.name);
    if (entry.isDirectory()) {
      // Recursively search in subdirectories
      fixAllComponentImports(fullPath);
    } else if (entry.isFile() && (entry.name.endsWith('.jsx') || entry.name.endsWith('.js'))) {
      let content = fs.readFileSync(fullPath, 'utf8');
      const originalContent = content;
      
      // Regex to find all relative imports to the components directory
      // Handles: from "./components/", from "../components/", from "../../components/", etc.
      const importRegex = /from\s+(['"])((\.\.\/)+|\.\/)components\//g;
      
      content = content.replace(importRegex, 'from $1@/components/');

      if (content !== originalContent) {
        console.log(`✅ Fixing component imports in ${fullPath}`);
        fs.writeFileSync(fullPath, content, 'utf8');
      }
    }
  }
}


// --- Exécution ---

function main() {
  console.log('--- Applying patches for local environment ---');
  
  // The specific patches are now less critical as the global fix is more robust,
  // but we can keep them for specific, non-import related changes.
  const patches = [
    {
      file: 'src/main.jsx',
      old_string: `ReactDOM.createRoot(document.getElementById('root')).render(
    <App />
)`,
      new_string: `import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>,
)`
    },
    {
        file: 'src/pages/Layout.jsx',
        old_string: `const { data: user } = useQuery({
    queryKey: ['current-user-layout'],
    queryFn: () => base44.auth.me(),
  });`,
        new_string: `  // const { data: user } = useQuery({
  //   queryKey: ['current-user-layout'],
  //   queryFn: () => base44.auth.me(),
  // });

  // Mock user data to prevent redirection and allow local development
  const user = {
    full_name: "Dev User",
    email: "dev@example.com",
    user_role: "admin", // You can change this to 'procurement', 'operator', 'client', etc. to test different navigation menus
    profile_picture: "https://i.pravatar.cc/150?u=a042581f4e29026024d",
  };
`
    }
  ];

  patches.forEach(patchInfo => {
    applyPatch(patchInfo.file, patchInfo);
  });

  console.log('--- Global component import fixes ---');
  fixAllComponentImports(path.join(projectRoot, 'src'));

  console.log('--- End of patching process ---');
}

main();
