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 captureDate = process.argv[2] ?? getKstDate();
const { baseUrl } = getCaptureRuntimeConfig(cwd);
const screenshotFileName = 'plan-board-mobile-memo-detail.png';
const { screenshotDir, screenshotPath, worklogPath, markdownImagePath } = resolveCapturePaths({
  cwd,
  captureDate,
  screenshotFileName,
});

const browser = await chromium.launch({ headless: true });
const context = await createCaptureContext(browser, {
  viewport: { width: 430, height: 932 },
  isMobile: true,
  hasTouch: true,
  deviceScaleFactor: 3,
});
const page = await context.newPage();

try {
  await ensureDirectory(screenshotDir);

  await page.goto(baseUrl, { waitUntil: 'networkidle' });
  await page.getByText('Plans').click();
  await page.getByRole('button', { name: '새 메모' }).click();

  const overlayCard = page.locator('.plan-board-page__overlay-card').first();
  await overlayCard.waitFor({ state: 'visible', timeout: 30000 });
  await overlayCard.screenshot({
    path: screenshotPath,
    animations: 'disabled',
  });

  await updateWorklogCaptureSection({
    worklogPath,
    captureDate,
    imageAlt: 'plan-board-mobile-memo-detail',
    markdownImagePath,
  });

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