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 componentId = process.argv[2];
const captureDate = process.argv[3] ?? getKstDate();
const { baseUrl } = getCaptureRuntimeConfig(cwd);

if (!componentId) {
  console.error('Usage: node scripts/capture-component-screenshot.mjs <component-id> [YYYY-MM-DD]');
  process.exit(1);
}

const screenshotFileName = `${componentId}.png`;
const { screenshotDir, screenshotPath, worklogPath, markdownImagePath } = resolveCapturePaths({
  cwd,
  captureDate,
  screenshotFileName,
});
const targetSelector = `#component-sample-${componentId}`;

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', 'apis');

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

  await page.waitForLoadState('networkidle').catch(() => {});

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

  await updateWorklogCaptureSection({
    worklogPath,
    captureDate,
    imageAlt: componentId,
    markdownImagePath,
  });

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