import process from 'node:process';
import { chromium } from 'playwright';
import { createCaptureContext, getCaptureRuntimeConfig } from './capture-auth-utils.mjs';
import { ensureDirectory, getKstDate, resolveCapturePaths, updateWorklogCaptureSection } from './worklog-capture-utils.mjs';

const cwd = process.cwd();
const menuGroup = process.argv[2] ?? 'docs';
const captureDate = process.argv[3] ?? getKstDate();
const { baseUrl } = getCaptureRuntimeConfig(cwd);

const supportedMenuGroups = new Set(['docs', 'plans']);

if (!supportedMenuGroups.has(menuGroup)) {
  console.error('Usage: node scripts/capture-menu-screenshot.mjs [docs|plans] [YYYY-MM-DD]');
  process.exit(1);
}

const screenshotFileName = `${menuGroup}-menu.png`;
const { screenshotDir, screenshotPath, worklogPath, markdownImagePath } = resolveCapturePaths({
  cwd,
  captureDate,
  screenshotFileName,
});

const browser = await chromium.launch({ headless: true });
const context = await createCaptureContext(browser, {
  viewport: { width: 1600, height: 1200 },
  deviceScaleFactor: 2,
});
const page = await context.newPage();

try {
  await ensureDirectory(screenshotDir);

  const targetUrl = new URL(baseUrl);
  targetUrl.searchParams.set('topMenu', menuGroup === 'docs' ? 'docs' : 'plans');

  await page.goto(targetUrl.toString(), { waitUntil: 'networkidle' });

  if (menuGroup === 'plans') {
    await page.getByLabel('설정').click();
    await page.locator('.app-header__settings-menu').first().waitFor({ state: 'visible', timeout: 30000 });
  }

  const target = page.locator('.app-shell').first();
  await target.waitFor({ state: 'visible', timeout: 30000 });
  await target.screenshot({
    path: screenshotPath,
    animations: 'disabled',
  });

  await updateWorklogCaptureSection({
    worklogPath,
    captureDate,
    imageAlt: screenshotFileName.replace('.png', ''),
    markdownImagePath,
  });

  console.log(`Saved: ${screenshotPath}`);
  console.log(`Linked in: ${worklogPath}`);
} finally {
  await context.close();
  await browser.close();
}
