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 SETTINGS_CAPTURE_PRESETS = {
  automation: {
    screenshotFileName: 'settings-app.png',
    triggerLabel: '앱 설정',
  },
  notification: {
    screenshotFileName: 'settings-notification.png',
    triggerLabel: '알림',
  },
};

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

if (!presetKey || !(presetKey in SETTINGS_CAPTURE_PRESETS)) {
  console.error(`Usage: node scripts/capture-settings-screenshot.mjs <${Object.keys(SETTINGS_CAPTURE_PRESETS).join('|')}> [YYYY-MM-DD]`);
  process.exit(1);
}

const preset = SETTINGS_CAPTURE_PRESETS[presetKey];
const { screenshotDir, screenshotPath, worklogPath, markdownImagePath } = resolveCapturePaths({
  cwd,
  captureDate,
  screenshotFileName: preset.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', 'plans');

  await page.goto(targetUrl.toString(), { waitUntil: 'networkidle' });
  await page.getByLabel('설정').click();
  await page.getByRole('button', { name: preset.triggerLabel }).click();

  const modal = page.locator('.ant-modal-root .ant-modal-content').last();
  await modal.waitFor({ state: 'visible', timeout: 30000 });
  await modal.screenshot({
    path: screenshotPath,
    animations: 'disabled',
  });

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

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