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 = 'main-content-fullscreen-toggle.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);

  await page.goto(baseUrl, { waitUntil: 'networkidle' });
  await page.getByLabel('콘텐츠 최대화').click();

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

  await updateWorklogCaptureSection({
    worklogPath,
    captureDate,
    imageAlt: 'main-content-fullscreen-toggle',
    markdownImagePath,
  });

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