const { chromium } = require('playwright');

// 目标URL
const TARGET_URL = 'http://localhost:3000';

// 门户网站常见特征关键词
const PORTAL_KEYWORDS = [
  '门户网站',
  '门户网',
  '信息门户',
  '企业门户',
  '门户首页',
  '门户系统',
  'Portal',
  '门户网站首页',
  '综合门户',
  '行业门户'
];

// 门户网站常见元素选择器
const PORTAL_SELECTORS = [
  'text=门户网站',
  'text=门户网',
  'text=信息门户',
  '.portal',
  '#portal',
  '[class*="portal"]',
  '[id*="portal"]'
];

(async () => {
  console.log('🚀 启动 Playwright 测试...');
  console.log(`🎯 目标URL: ${TARGET_URL}`);
  console.log('');

  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();

  try {
    // 1. 访问页面
    console.log('📄 正在加载页面...');
    const response = await page.goto(TARGET_URL, {
      waitUntil: 'networkidle',
      timeout: 30000
    });

    if (!response) {
      throw new Error('页面加载失败：无响应');
    }

    if (!response.ok()) {
      throw new Error(`页面加载失败：HTTP ${response.status()}`);
    }

    console.log(`✅ 页面加载成功 (HTTP ${response.status()})`);
    console.log('');

    // 2. 获取页面基本信息
    const title = await page.title();
    const url = page.url();
    const html = await page.content();
    const bodyText = await page.locator('body').innerText();

    console.log('📊 页面基本信息：');
    console.log(`   - 标题: ${title}`);
    console.log(`   - URL: ${url}`);
    console.log('');

    // 3. 验证页面不是门户网站 - 多维度检查
    let isPortal = false;
    const failureReasons = [];

    // 3.1 检查标题中是否包含门户关键词
    console.log('🔍 检查1: 页面标题分析...');
    const titleLower = title.toLowerCase();
    for (const keyword of PORTAL_KEYWORDS) {
      if (titleLower.includes(keyword.toLowerCase())) {
        isPortal = true;
        failureReasons.push(`标题包含门户关键词: "${keyword}"`);
        console.log(`   ❌ 发现门户关键词: "${keyword}"`);
      }
    }
    if (!isPortal) {
      console.log('   ✅ 标题未包含门户关键词');
    }

    // 3.2 检查页面内容中是否包含门户关键词
    console.log('');
    console.log('🔍 检查2: 页面内容分析...');
    const bodyTextLower = bodyText.toLowerCase();
    const foundKeywords = [];
    for (const keyword of PORTAL_KEYWORDS) {
      if (bodyTextLower.includes(keyword.toLowerCase())) {
        foundKeywords.push(keyword);
      }
    }
    if (foundKeywords.length > 0) {
      isPortal = true;
      failureReasons.push(`页面内容包含门户关键词: ${foundKeywords.join(', ')}`);
      console.log(`   ❌ 发现门户关键词: ${foundKeywords.join(', ')}`);
    } else {
      console.log('   ✅ 页面内容未包含门户关键词');
    }

    // 3.3 检查是否存在门户相关的DOM元素
    console.log('');
    console.log('🔍 检查3: DOM元素分析...');
    let foundPortalElements = false;
    for (const selector of PORTAL_SELECTORS) {
      const count = await page.locator(selector).count();
      if (count > 0) {
        foundPortalElements = true;
        isPortal = true;
        failureReasons.push(`发现门户相关DOM元素: ${selector} (数量: ${count})`);
        console.log(`   ❌ 发现门户相关元素: ${selector} (${count}个)`);
      }
    }
    if (!foundPortalElements) {
      console.log('   ✅ 未发现门户相关DOM元素');
    }

    // 3.4 检查meta标签
    console.log('');
    console.log('🔍 检查4: Meta标签分析...');
    const metaDescription = await page.locator('meta[name="description"]').getAttribute('content').catch(() => '');
    const metaKeywords = await page.locator('meta[name="keywords"]').getAttribute('content').catch(() => '');

    const metaContent = `${metaDescription} ${metaKeywords}`.toLowerCase();
    const foundMetaKeywords = [];
    for (const keyword of PORTAL_KEYWORDS) {
      if (metaContent.includes(keyword.toLowerCase())) {
        foundMetaKeywords.push(keyword);
      }
    }
    if (foundMetaKeywords.length > 0) {
      isPortal = true;
      failureReasons.push(`Meta标签包含门户关键词: ${foundMetaKeywords.join(', ')}`);
      console.log(`   ❌ Meta标签包含门户关键词: ${foundMetaKeywords.join(', ')}`);
    } else {
      console.log('   ✅ Meta标签未包含门户关键词');
    }

    // 4. 输出验证结果
    console.log('');
    console.log('='.repeat(60));
    if (isPortal) {
      console.log('❌ 测试失败：页面被识别为门户网站');
      console.log('');
      console.log('失败原因：');
      failureReasons.forEach((reason, index) => {
        console.log(`   ${index + 1}. ${reason}`);
      });
      process.exit(1);
    } else {
      console.log('✅ 测试通过：页面不是门户网站');
      console.log('');
      console.log('验证详情：');
      console.log('   ✓ 标题不包含门户关键词');
      console.log('   ✓ 页面内容不包含门户关键词');
      console.log('   ✓ 不存在门户相关DOM元素');
      console.log('   ✓ Meta标签不包含门户关键词');
      console.log('');
      console.log('页面特征：');
      console.log(`   - 标题: "${title}"`);
      console.log(`   - 描述: "${metaDescription || 'N/A'}"`);
      console.log(`   - 内容长度: ${bodyText.length} 字符`);
    }
    console.log('='.repeat(60));

    // 5. 截图保存
    await page.screenshot({ path: './test-screenshot.png', fullPage: true });
    console.log('');
    console.log('📸 截图已保存: ./test-screenshot.png');

  } catch (error) {
    console.error('');
    console.error('❌ 测试执行出错:');
    console.error(`   ${error.message}`);
    process.exit(1);
  } finally {
    await browser.close();
    console.log('');
    console.log('🎯 测试完成');
  }
})();
