/**
 * 按最新人工录制（flock-logged-in-20260715-155553）有头可视化回放：
 * 登录 → home → New Quote → Quick → 填表 → 提交 → 解析报价
 *
 *   npm run visual:flock-logged-in
 *   # 或指定客户
 *   FLOCK_VISUAL_CUSTOMER_ID=CUST_001 npm run visual:flock-logged-in
 */
import { loadDevEnv } from "@/lib/dev-env";

loadDevEnv();

process.env.RPA_HEADED = "true";
process.env.RPA_HEADLESS = "false";
if (!process.env.RPA_SLOW_MO_MS?.trim()) {
  process.env.RPA_SLOW_MO_MS = "250";
}
process.env.FLOCK_WORKER_REUSE_SESSION = "false";

import { getCustomerProviderLogin } from "@/modules/customer/provider-credentials";
import { runWithFlockLoginContext } from "@/lib/flock/login-context";
import { runFlockVisualChain } from "@/workers/rpa/flock/visual-chain";
import type { FlockQuoteInput } from "@/workers/rpa/flock/types";

function pickupDateNearRecording(): string {
  // 录制选了 17 号；取「今天起 ≥2 天」的工作日口径简化用日历日
  const d = new Date();
  d.setDate(d.getDate() + 2);
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  const yyyy = d.getFullYear();
  return `${mm}/${dd}/${yyyy}`;
}

/** 与 155553 录制参数对齐 */
const SAMPLE: FlockQuoteInput = {
  formMode: "logged_in_quick",
  pickupDate: pickupDateNearRecording(),
  pickupZip: "90248",
  deliveryZip: "15222",
  palletCount: 2,
  totalWeightLb: 500,
  lengthIn: 48,
  widthIn: 40,
  heightIn: 48,
  pickupLocationType: "business_with_dock",
  deliveryLocationType: "business_with_dock",
  packagingType: "bags",
  freightClass: "density",
  description: "papers",
  stackable: true,
  additionalServices: ["unloading"],
  vehicleTypes: ["box_truck", "dry_van", "refrigerated"],
  callBeforePickup: false,
};

async function main(): Promise<void> {
  const customerId =
    process.env.FLOCK_VISUAL_CUSTOMER_ID?.trim() || "CUST_001";
  const login = await getCustomerProviderLogin(customerId, "flock");
  if (!login) {
    console.error(
      `[visual-flock] 客户 ${customerId} 无可用 Flock 账密（解密失败或未配置）`,
    );
    process.exit(1);
  }

  console.log("=== Flock 登录态可视化回放（对齐人工录制）===");
  console.log(`customer=${customerId} email=${login.email.slice(0, 2)}***`);
  console.log(
    `sample ${SAMPLE.pickupZip}→${SAMPLE.deliveryZip} qty=${SAMPLE.palletCount} bags density`,
  );
  console.log(`pickupDate=${SAMPLE.pickupDate} headed=true slowMo=${process.env.RPA_SLOW_MO_MS}`);
  console.log("请注视弹出的 Chrome 窗口…");

  const result = await runWithFlockLoginContext(login, "customer", () =>
    runFlockVisualChain({ input: SAMPLE }),
  );

  if (!result.ok) {
    console.error(`[visual-flock] FAIL: ${result.errorMessage ?? "unknown"}`);
    process.exit(1);
  }

  console.log(
    `[visual-flock] OK ref=${result.reference ?? "-"} quotes=${result.quotes
      .map((q) => `${q.label}:$${q.totalUsd}`)
      .join(", ")}`,
  );
  process.exit(0);
}

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