import type { QuoteRequest } from "@/modules/providers/quote-provider";
import { isRpaAddressMockMode } from "@/lib/rpa/address-mode";
import { isRpaHumanSubmitStrict, isRpaAddressRushMode, isBlindAddressFlowActive } from "@/lib/rpa/env";
import { assertRPAContext } from "@/workers/rpa/kernel/context-validator";
import type { RPAContext } from "@/workers/rpa/kernel/context";
import { runKernelSubStep } from "@/workers/rpa/kernel/step-guard";
import {
  assertBothAddressesLocked,
  settleAddressFieldsForCargo,
  waitForCargoCommittedState,
} from "@/workers/rpa/cargo-lock";
import { fillCargoInDrawer } from "@/workers/rpa/fill-cargo-in-drawer";

/**
 * Kernel 货物填表：动态 drawer 填写 + commit 闸门
 */
export async function fillCargoStep(
  ctx: RPAContext,
  req: QuoteRequest,
  options?: { skipAddressLock?: boolean },
): Promise<void> {
  assertRPAContext(ctx, "fillCargoStep");

  const rush = isRpaAddressRushMode();
  const humanStrict = isRpaHumanSubmitStrict();
  const rushShortcuts = rush && !humanStrict;
  const widgetSelector = ctx.selectors.resolve("RPA_SELECTOR_QUOTE_WIDGET");

  if (!rushShortcuts) {
    await runKernelSubStep("fillCargo", "settleAddressFieldsForCargo", () =>
      settleAddressFieldsForCargo(ctx.page, widgetSelector),
    );
  } else {
    console.log("[rpa] visual-rush: 跳过 fillCargo 前地址 settle");
  }

  if (!isRpaAddressMockMode() && !options?.skipAddressLock && !rushShortcuts) {
    await assertBothAddressesLocked(ctx.page, widgetSelector);
  } else if (rushShortcuts) {
    console.log("[rpa] visual-rush: 跳过 fillCargo 双地址锁定闸门");
  } else if (options?.skipAddressLock) {
    console.log("[rpa] axel-place-prefetch: 跳过 fillCargo 双地址锁定闸门");
  } else {
    console.log("[rpa] address-mock: 跳过 fillCargo 双地址锁定闸门");
  }

  const { expected, landingPopoverFilled } = await runKernelSubStep(
    "fillCargo",
    "fillCargoInDrawer",
    () =>
      fillCargoInDrawer(ctx.page, widgetSelector, {
        palletCount: req.palletCount,
        weightLbPerPallet: req.weightLb,
        dimsIn: req.dimsIn,
        blindFlow: isBlindAddressFlowActive(ctx),
      }),
  );

  if ((landingPopoverFilled || rush) && rushShortcuts) {
    console.log("[rpa] visual-rush: 跳过 waitForCargoCommittedState");
  } else if (landingPopoverFilled && humanStrict) {
    console.log("[rpa] human-submit-strict: landing 已填，等待 cargo commit");
    await runKernelSubStep("fillCargo", "waitForCargoCommittedState", () =>
      waitForCargoCommittedState(ctx.page, widgetSelector, expected),
    );
  } else if (landingPopoverFilled) {
    console.log("[rpa] fillCargo: landing 视觉已填，跳过 widget 摘要闸门");
  } else {
    await runKernelSubStep("fillCargo", "waitForCargoCommittedState", () =>
      waitForCargoCommittedState(ctx.page, widgetSelector, expected),
    );
  }
}
