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

const e2eDir = path.join(__dirname, 'tests', 'e2e');
const files = fs.readdirSync(e2eDir).filter(f => f.endsWith('.spec.ts'));

const goodAuthBlock = `  test.beforeEach(async ({ page }) => {
    // Navigate to auth page
    await page.goto(\`\${baseURL}/auth\`);
    
    // Wait for either the auth form OR the app dashboard to indicate login state
    const authForm = page.locator('form').filter({ hasText: /sign in|login|đăng nhập/i });
    const appDashboard = page.locator('.main-layout, [data-testid="app-container"], nav').first();
    
    try {
      await Promise.race([
        authForm.waitFor({ state: 'visible', timeout: 5000 }),
        appDashboard.waitFor({ state: 'visible', timeout: 5000 })
      ]);
    } catch {
      // Ignore initial wait failure
    }

    // Attempt login if username input is visible
    const usernameInput = page.getByPlaceholder(/Enter your username/i).or(page.locator('input[name="username"]', { hasText: '' })).or(page.locator('input').first());
    
    let isLoginFormVisible = false;
    try {
      await usernameInput.waitFor({ state: 'visible', timeout: 2000 });
      isLoginFormVisible = true;
    } catch {
      isLoginFormVisible = false;
    }

    if (isLoginFormVisible) {
      const passwordInput = page.getByPlaceholder(/Enter your password/i).or(page.locator('input[type="password"]'));
      const submitButton = page.getByRole('button', { name: /sign in|login|đăng nhập/i }).or(page.locator('button[type="submit"]')).first();
      
      await usernameInput.fill('e2etest');
      await passwordInput.fill('Test12345!');
      await submitButton.click();
      await page.waitForURL(/.*app(\\/.*)?/, { timeout: 15000 }).catch(() => {});
    }
  });`;

for (const file of files) {
  if (['comments-anonymous.spec.ts', 'comments-private-anonymous.spec.ts', 'auth.spec.ts'].includes(file)) continue; // skip already fixed or auth-specific
  
  const filePath = path.join(e2eDir, file);
  let content = fs.readFileSync(filePath, 'utf8');
  
  // Replace beforeEach block
  const beforeEachRegex = /test\.beforeEach\(async \(\{ page \}\) => \{[\s\S]*?\}\s*\n\s*\}\);\n/;
  if (beforeEachRegex.test(content)) {
    content = content.replace(beforeEachRegex, goodAuthBlock + '\n');
  }

  // Strip arbitrary try-catch blocks that skip tests
  // We match try { ... } catch { console.log('... skipped ...') }
  const tryCatchRegex = /try\s*\{([\s\S]*?)\}\s*catch(?:\s*\([^)]*\))?\s*\{\s*console\.log\(['"][^'"]*skipped[^'"]*['"](?:,\s*[^)]*)?\);\s*\}/g;
  content = content.replace(tryCatchRegex, '$1');

  // Also replace `if (await el.isVisible().catch(() => false))` with proper logic if any
  const isVisibleRegex = /if\s*\(\!await\s+(\w+)\.isVisible\(\)\.catch\(\(\)\s*=>\s*false\)\)\s*\{/g;
  content = content.replace(isVisibleRegex, 'try { await $1.waitFor({ state: \'visible\', timeout: 3000 }); } catch {');

  const isVisibleTrueRegex = /if\s*\(await\s+(\w+)\.isVisible\(\)\.catch\(\(\)\s*=>\s*false\)\)\s*\{/g;
  content = content.replace(isVisibleTrueRegex, 'let is$1Vis = false; try { await $1.waitFor({ state: \'visible\', timeout: 3000 }); is$1Vis = true; } catch {} if (is$1Vis) {');

  fs.writeFileSync(filePath, content, 'utf8');
  console.log(`Updated ${file}`);
}
