import type { QuoteItem, QuoteRequest } from "@/modules/providers/quote-provider";
import { isRpaAddressRushMode } from "@/lib/rpa/env";
import { assertRPAContext } from "@/workers/rpa/kernel/context-validator";
import type { RPAContext } from "@/workers/rpa/kernel/context";
import { fillAddressStep } from "@/workers/rpa/kernel/steps/address-step";
import { fillCargoStep } from "@/workers/rpa/kernel/steps/cargo-step";
import { validateResult } from "@/workers/rpa/kernel/steps/quote-step";
import { captureQuotesDirectFirst } from "@/workers/rpa/quote-capture/quote-strategy";

/** MotherShip 询价主流程（thin orchestration 唯一入口） */
export async function runMothershipQuoteKernel(
  ctx: RPAContext,
  req: QuoteRequest,
): Promise<QuoteItem[]> {
  assertRPAContext(ctx, "runMothershipQuoteKernel");
  console.log("[rpa] step: fillAddress");
  await fillAddressStep(ctx, req);

  console.log("[rpa] step: fillCargo");
  await fillCargoStep(ctx, req);

  console.log("[rpa] step: captureQuotes（点击 Get a freight quote）");
  const { items, source } = await captureQuotesDirectFirst(ctx, req);
  console.log(
    `[rpa] quote-acquired: source=${source} tiers=${items.length}`,
  );

  if (!isRpaAddressRushMode()) {
    validateResult(items);
  } else if (items.length > 0) {
    validateResult(items);
  } else {
    console.log("[rpa] visual-rush: 报价解析为空，以 sign-up-quote 落页为准");
  }
  return items;
}
