/**
 * CloakBrowser test harness for the AutoShopee Kit extension.
 *
 * Launches the stealth Chromium (bypasses Shopee anti-bot / DataDome) with the
 * built unpacked extension loaded and a PERSISTENT profile, so you log in to
 * Shopee once and stay logged in for every future run.
 *
 * Usage:
 *   node scripts/cloak-shopee-test.mjs                 # search?keyword=ipad, auto-verify spy boxes
 *   node scripts/cloak-shopee-test.mjs "op lung ipad"  # custom keyword
 *   node scripts/cloak-shopee-test.mjs --login         # just open Shopee to log in
 *
 * First run: it will land on the login page. Log in manually in the window.
 * The session is saved in .cloak-profile/ (git-ignored) and reused next time.
 *
 * In search mode the script waits for the extension's spy boxes
 * (#autoshopee_product_search_*), reads their text, and prints how many show
 * real data vs the "???" empty state — a PASS/FAIL verdict for the fetch fix.
 * The window then stays open until you press Ctrl+C.
 */
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { launchPersistentContext } from 'cloakbrowser';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');

const EXTENSION_PATH = path.join(ROOT, 'dist', 'chrome-mv3-dev');
const USER_DATA_DIR = path.join(ROOT, '.cloak-profile');

const main = async () => {
  console.log('▶ Launching Browser  …');
  console.log(`✅ Loaded extension: ${EXTENSION_PATH}`);
  console.log(`✅ Loaded profile: ${USER_DATA_DIR}`);

  const ctx = await launchPersistentContext({
    userDataDir: USER_DATA_DIR,
    headless: false,
    extensionPaths: [
      EXTENSION_PATH,
    ],
    viewport: null,
    args: ['--start-maximized'],
  });

  const page = ctx.pages()[0] || (await ctx.newPage());

  await page.goto('https://shopee.vn/', { waitUntil: 'domcontentloaded' }).catch(() => {});

  return ctx;
};

main().catch((err) => {
  console.error('CloakBrowser test failed:', err);
  process.exit(1);
});
