/**
 * Flock 登录探针：校验 FLOCK_LOGIN_* 可登录并写回 storage
 *
 *   FLOCK_LOGIN_EMAIL=... FLOCK_LOGIN_PASSWORD=... npm run probe:flock-login
 */
import fs from "node:fs";
import path from "node:path";
import {
  getFlockLoginCredentials,
  getFlockLoginUrl,
  getFlockQuoteUrl,
  getFlockStorageStatePath,
  hasFlockLoginCredentials,
} from "@/lib/flock/env";
import { launchRpaBrowser } from "@/lib/rpa/browser-launch";
import { createRpaBrowserContext } from "@/lib/rpa/browser-context";
import { gotoWithResilience } from "@/lib/rpa/page-goto";
import { waitForFlockQuoteForm } from "@/workers/rpa/flock/form-interactions";
import { ensureFlockLoggedIn } from "@/workers/rpa/flock/login";

async function main(): Promise<void> {
  if (!hasFlockLoginCredentials()) {
    console.error(
      "[probe:flock-login] 请设置 FLOCK_LOGIN_EMAIL 与 FLOCK_LOGIN_PASSWORD",
    );
    process.exit(1);
  }

  const creds = getFlockLoginCredentials()!;
  console.log(
    `[probe:flock-login] email=${creds.email.slice(0, 3)}*** loginUrl=${getFlockLoginUrl()}`,
  );

  const headless = process.env.RPA_HEADLESS !== "false";
  const browser = await launchRpaBrowser({ headless, incognito: false });
  try {
    const context = await createRpaBrowserContext(browser);
    const page = await context.newPage();
    await gotoWithResilience(page, getFlockQuoteUrl());

    const login = await ensureFlockLoggedIn(page, context);
    if (!login.ok) {
      console.error(`[probe:flock-login] FAIL ${login.errorMessage}`);
      process.exit(1);
    }

    await gotoWithResilience(page, getFlockQuoteUrl());
    const formOk = await waitForFlockQuoteForm(page);
    const statePath = getFlockStorageStatePath();
    const abs = path.isAbsolute(statePath)
      ? statePath
      : path.join(process.cwd(), statePath);
    const stored = fs.existsSync(abs);

    console.log(
      `[probe:flock-login] OK didLogin=${login.didLogin} form=${formOk} storage=${stored ? abs : "未写入"}`,
    );
    process.exit(formOk ? 0 : 2);
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  console.error("[probe:flock-login] fatal", error);
  process.exit(1);
});
