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 = 'search-command.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.evaluate(() => {
    const sensor = Array.from(document.querySelectorAll('div')).find((element) => {
      const style = window.getComputedStyle(element);
      return (
        style.position === 'fixed' &&
        style.top === '0px' &&
        style.right === '0px' &&
        style.touchAction === 'none' &&
        element.childElementCount === 0
      );
    });

    if (!sensor) {
      throw new Error('Search gesture sensor not found.');
    }

    const rect = sensor.getBoundingClientRect();
    const startX = rect.right - 24;
    const startY = rect.top + 18;
    const endY = startY + 120;

    const createTouch = (clientY) =>
      new Touch({
        identifier: 1,
        target: sensor,
        clientX: startX,
        clientY,
        radiusX: 12,
        radiusY: 12,
        rotationAngle: 0,
        force: 1,
      });

    const dispatch = (type, touches) => {
      sensor.dispatchEvent(
        new TouchEvent(type, {
          bubbles: true,
          cancelable: true,
          touches,
          targetTouches: touches,
          changedTouches: touches,
        }),
      );
    };

    dispatch('touchstart', [createTouch(startY)]);
    dispatch('touchmove', [createTouch(endY)]);
    dispatch('touchend', []);
  });

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

  await updateWorklogCaptureSection({
    worklogPath,
    captureDate,
    imageAlt: 'search-command',
    markdownImagePath,
  });

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