import { test, expect } from '@playwright/test';
import { STAGING_URL } from './config/staging-config';

/**
 * Comprehensive test to investigate the current state of plugins on staging
 */
test.describe('Staging Plugin Investigation', () => {
  test('Check WordPress admin and installed plugins', async ({ page }) => {
    console.log('Investigation: Checking WordPress admin and plugin status');
    
    // First, check if we can access the site
    await page.goto(STAGING_URL);
    await page.waitForLoadState('networkidle');
    await page.screenshot({ path: 'test-results/investigation/homepage.png' });
    
    console.log('Step 1: Getting homepage info');
    const title = await page.title();
    console.log(`Homepage title: ${title}`);
    
    // Try to access wp-admin
    console.log('Step 2: Attempting to access wp-admin');
    await page.goto(`${STAGING_URL}/wp-admin/`);
    await page.waitForLoadState('networkidle');
    
    const adminUrl = page.url();
    console.log(`Admin URL: ${adminUrl}`);
    
    if (adminUrl.includes('wp-login.php')) {
      console.log('Redirected to login page - this is expected');
      
      // Try to login if we have credentials
      // First, let's see if there are any test credentials we can use
      const hasUsernameField = await page.locator('input[name="log"]').count() > 0;
      const hasPasswordField = await page.locator('input[name="pwd"]').count() > 0;
      
      console.log(`Login form detected - Username field: ${hasUsernameField}, Password field: ${hasPasswordField}`);
      
      // Let's try some common test credentials
      if (hasUsernameField && hasPasswordField) {
        console.log('Step 3: Attempting login with test credentials');
        
        // Try common test credentials
        const testCredentials = [
          { username: 'test_trainer', password: 'password123' },
          { username: 'admin', password: 'admin' },
          { username: 'test', password: 'test' }
        ];
        
        for (const cred of testCredentials) {
          console.log(`Trying: ${cred.username}`);
          
          await page.fill('input[name="log"]', cred.username);
          await page.fill('input[name="pwd"]', cred.password);
          await page.click('input[type="submit"]');
          await page.waitForLoadState('networkidle');
          
          const currentUrl = page.url();
          if (!currentUrl.includes('wp-login.php')) {
            console.log(`Successfully logged in with: ${cred.username}`);
            break;
          } else {
            console.log(`Login failed for: ${cred.username}`);
            // Go back to login page for next attempt
            await page.goto(`${STAGING_URL}/wp-admin/`);
            await page.waitForLoadState('networkidle');
          }
        }
      }
    }
    
    const finalUrl = page.url();
    console.log(`Final URL after login attempts: ${finalUrl}`);
    
    if (finalUrl.includes('wp-admin') && !finalUrl.includes('wp-login.php')) {
      console.log('Step 4: Successfully accessed wp-admin, checking plugins');
      
      // Go to plugins page
      await page.goto(`${STAGING_URL}/wp-admin/plugins.php`);
      await page.waitForLoadState('networkidle');
      await page.screenshot({ path: 'test-results/investigation/plugins-page.png' });
      
      // Check if we can see the plugins page
      const pluginsPageContent = await page.textContent('body');
      const isPluginsPage = pluginsPageContent?.includes('Plugin') || pluginsPageContent?.includes('Activate');
      
      console.log(`On plugins page: ${isPluginsPage}`);
      
      if (isPluginsPage) {
        // Look for HVAC plugin
        const hvacPlugin = page.locator('tr:has-text("HVAC Community Events")');
        const hvacPluginCount = await hvacPlugin.count();
        console.log(`HVAC Community Events plugin found: ${hvacPluginCount > 0}`);
        
        if (hvacPluginCount > 0) {
          const pluginStatus = await hvacPlugin.locator('.active').count() > 0 ? 'active' : 'inactive';
          console.log(`HVAC plugin status: ${pluginStatus}`);
        }
        
        // Look for TEC plugins
        const tecPlugins = page.locator('tr:has-text("The Events Calendar")');
        const tecCount = await tecPlugins.count();
        console.log(`The Events Calendar related plugins found: ${tecCount}`);
        
        // List all visible plugins
        const pluginRows = page.locator('table.plugins tr[data-slug]');
        const pluginCount = await pluginRows.count();
        console.log(`Total plugins found: ${pluginCount}`);
        
        for (let i = 0; i < Math.min(pluginCount, 10); i++) {
          const pluginName = await pluginRows.nth(i).locator('.plugin-title strong').textContent();
          const isActive = await pluginRows.nth(i).locator('.active').count() > 0;
          console.log(`Plugin ${i + 1}: ${pluginName} (${isActive ? 'Active' : 'Inactive'})`);
        }
      }
    } else {
      console.log('Could not access wp-admin area');
    }
    
    console.log('Investigation completed');
  });
  
  test('Check if plugin files exist via web requests', async ({ page }) => {
    console.log('Step 1: Testing direct access to plugin files');
    
    // Try to access plugin files directly
    const pluginPaths = [
      '/wp-content/plugins/hvac-community-events/hvac-community-events.php',
      '/wp-content/plugins/hvac-community-events/includes/class-hvac-community-events.php',
      '/wp-content/plugins/hvac-community-events/assets/css/hvac-dashboard.css',
      '/wp-content/plugins/hvac-community-events/assets/js/hvac-dashboard.js'
    ];
    
    for (const path of pluginPaths) {
      try {
        const response = await page.request.get(`${STAGING_URL}${path}`);
        console.log(`${path}: ${response.status()} ${response.statusText()}`);
        
        if (response.status() === 200) {
          const contentType = response.headers()['content-type'];
          console.log(`  Content-Type: ${contentType}`);
          
          if (path.endsWith('.php')) {
            const content = await response.text();
            const hasPluginHeader = content.includes('Plugin Name:') || content.includes('HVAC Community Events');
            console.log(`  Contains plugin header: ${hasPluginHeader}`);
          }
        }
      } catch (error) {
        console.log(`${path}: Error - ${error}`);
      }
    }
    
    console.log('Plugin file access check completed');
  });
});