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

const email = process.env.QC_EMAIL;
const password = process.env.QC_PASSWORD;
const baseUrl = process.env.QC_BASE_URL || 'http://qc.yyangpt.cn/';
const outputDir = path.resolve(__dirname);
const assetDir = path.join(outputDir, 'assets');

if (!email || !password) {
  console.error('QC_EMAIL and QC_PASSWORD are required.');
  process.exit(1);
}

fs.mkdirSync(assetDir, { recursive: true });

const rows = [];
const now = new Date().toISOString();

function csvCell(value) {
  const text = String(value ?? '');
  return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
}

function filenameFromText(text) {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 80) || 'page';
}

async function stabilize(page) {
  await page.waitForLoadState('domcontentloaded').catch(() => {});
  await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
  await page.waitForTimeout(1200);
  await page.addStyleTag({
    content: `
      *, *::before, *::after {
        transition-duration: 0s !important;
        animation-duration: 0s !important;
        animation-delay: 0s !important;
      }
    `
  }).catch(() => {});
}

async function visibleSummary(page) {
  return page.evaluate(() => {
    const h1 = document.querySelector('h1')?.innerText?.trim() || '';
    const h2 = document.querySelector('h2')?.innerText?.trim() || '';
    const title = document.title || '';
    const text = document.body.innerText.replace(/\s+/g, ' ').trim().slice(0, 240);
    return { title, h1, h2, text, url: location.href };
  });
}

async function capture(page, slug, route, note = '') {
  await stabilize(page);
  const file = `${slug}.png`;
  const screenshotPath = path.join(assetDir, file);
  await page.screenshot({ path: screenshotPath, fullPage: true });
  const summary = await visibleSummary(page);
  rows.push({
    id: String(rows.length + 1).padStart(2, '0'),
    slug,
    route,
    file: `assets/${file}`,
    url: summary.url,
    title: summary.title,
    h1: summary.h1,
    h2: summary.h2,
    note,
    captured_at: now
  });
}

async function clickTextIfVisible(page, text) {
  const locator = page.getByText(text, { exact: true }).first();
  if (await locator.isVisible().catch(() => false)) {
    await locator.click();
    return true;
  }
  return false;
}

async function login(page) {
  await page.goto(`${baseUrl}#/login`, { waitUntil: 'networkidle', timeout: 30000 });
  await capture(page, '00-login-account', '#/login', '登录页：账号登录模式，未输入账号密码。');

  if (await clickTextIfVisible(page, '首次登录')) {
    await capture(page, '00-login-first-time', '#/login', '登录页：首次登录邮箱验证模式。');
  }

  if (await clickTextIfVisible(page, '忘记密码')) {
    await capture(page, '00-login-forgot-password', '#/login', '登录页：忘记密码/重置密码模式。');
  }

  await page.goto(`${baseUrl}#/login`, { waitUntil: 'networkidle', timeout: 30000 });
  await page.getByRole('tab', { name: '账号登录' }).click();
  await page.waitForTimeout(500);
  const visibleInputs = page.locator('input:visible');
  await visibleInputs.nth(0).fill(email);
  await visibleInputs.nth(1).fill(password);
  await page.locator('button:visible').filter({ hasText: /登\s*录/ }).click();
  await page.waitForURL(/#\/(?!login)/, { timeout: 15000 }).catch(() => {});
  await page.waitForTimeout(2500);
}

async function captureCollectionSteps(page) {
  await page.goto(`${baseUrl}#/collection`, { waitUntil: 'networkidle', timeout: 30000 });
  await capture(page, '02-collection-step-1-form', '#/collection', '采集工作台：在线小表单步骤。');

  const nextButton = page.getByRole('button', { name: '下一步' });
  if (await nextButton.first().isVisible().catch(() => false)) {
    await nextButton.first().click();
    await capture(page, '02-collection-step-2-photos', '#/collection', '采集工作台：现场照片步骤。');
  }
  if (await nextButton.first().isVisible().catch(() => false)) {
    await nextButton.first().click();
    await capture(page, '02-collection-step-3-audio', '#/collection', '采集工作台：语音访谈步骤。');
  }
}

async function captureAdminTabs(page) {
  await page.goto(`${baseUrl}#/admin`, { waitUntil: 'networkidle', timeout: 30000 });
  await capture(page, '07-admin-default', '#/admin', '管理后台默认视图。');

  const tabTexts = await page.locator('[role="tab"]').evaluateAll(elements =>
    elements.map(el => el.innerText.trim()).filter(Boolean)
  ).catch(() => []);

  const uniqueTabs = [...new Set(tabTexts)];
  for (const tabText of uniqueTabs) {
    const tab = page.getByRole('tab', { name: tabText }).first();
    if (await tab.isVisible().catch(() => false)) {
      await tab.click();
      await capture(page, `07-admin-tab-${filenameFromText(tabText)}`, '#/admin', `管理后台 Tab：${tabText}`);
    }
  }
}

(async () => {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 1000 },
    deviceScaleFactor: 1,
    locale: 'zh-CN'
  });
  const page = await context.newPage();

  try {
    await login(page);
    await page.goto(`${baseUrl}#/`, { waitUntil: 'networkidle', timeout: 30000 });
    await capture(page, '01-home-dashboard', '#/', '首页：管理员工作入口、售前资料沉淀流程和团队录入概览。');

    await captureCollectionSteps(page);

    const routes = [
      ['03-history', '#/history', '历史录入页面。'],
      ['04-completion', '#/completion', '采集完整度页面。'],
      ['05-statistics', '#/statistics', '采集统计页面。'],
      ['06-export', '#/export', '资料导出中心页面。']
    ];

    for (const [slug, hash, note] of routes) {
      await page.goto(`${baseUrl}${hash}`, { waitUntil: 'networkidle', timeout: 30000 });
      await capture(page, slug, hash, note);
    }

    await captureAdminTabs(page);
  } finally {
    await browser.close();
  }

  const csv = [
    ['id', 'slug', 'route', 'file', 'url', 'title', 'h1', 'h2', 'note', 'captured_at'].join(','),
    ...rows.map(row => ['id', 'slug', 'route', 'file', 'url', 'title', 'h1', 'h2', 'note', 'captured_at'].map(key => csvCell(row[key])).join(','))
  ].join('\n') + '\n';
  fs.writeFileSync(path.join(outputDir, 'screenshot-index.csv'), csv, 'utf8');
  fs.writeFileSync(path.join(outputDir, 'screenshot-index.json'), JSON.stringify(rows, null, 2), 'utf8');

  console.log(JSON.stringify({ outputDir, count: rows.length, files: rows.map(row => row.file) }, null, 2));
})().catch(error => {
  console.error(error);
  process.exit(1);
});
