/**
 * Flock Freight selector 规格（env 覆盖 + 录制回退）
 * 录制参考：.rpa/recordings/flock-manual-20260713-152051.js
 */
import {
  fillFirstVisibleFromSpecs,
  getSelectorSpecs,
} from "@/lib/rpa/selector-specs";
import type { Page } from "playwright";

const FLOCK_BUILTIN_FALLBACKS: Record<string, string[]> = {
  FLOCK_SELECTOR_PICKUP_ZIP: [
    'role=textbox[name="Pickup ZIP Code"]',
    'role=textbox[name="取件邮政编码"]',
  ],
  FLOCK_SELECTOR_PICKUP_DATE: [
    'role=textbox[name="Pickup Date *"]',
    'role=textbox[name="Pickup Date"]',
    'role=textbox[name="取货日期"]',
  ],
  FLOCK_SELECTOR_DELIVERY_ZIP: [
    'role=textbox[name="Delivery ZIP Code"]',
    'role=textbox[name="投递邮政编码"]',
  ],
  FLOCK_SELECTOR_PALLET_COUNT: [
    'role=textbox[name="Number of pallets"]',
    'role=textbox[name="Quantity"]',
    'role=textbox[name="托盘数量"]',
  ],
  FLOCK_SELECTOR_TOTAL_WEIGHT: [
    'role=textbox[name="Total shipment weight (lbs)"]',
    'role=textbox[name="Total Weight (lbs)"]',
    'role=textbox[name="总运输重量"]',
  ],
  FLOCK_SELECTOR_LENGTH: [
    'role=textbox[name="Length (in)"]',
    'role=textbox[name="长度"]',
  ],
  FLOCK_SELECTOR_WIDTH: [
    'role=textbox[name="Width (in)"]',
    'role=textbox[name="宽度"]',
  ],
  FLOCK_SELECTOR_HEIGHT: [
    'role=textbox[name="Height (in)"]',
    'role=textbox[name="高度"]',
  ],
  FLOCK_SELECTOR_NEXT: [
    'role=button[name="Generate my quote"]',
    '[data-testid="anonymous_marketing_lead_quote_request_page__quote_request__submit_button"]',
    'role=button[name="Next"]',
    'role=button[name="下一个"]',
  ],
  FLOCK_SELECTOR_CARD_DIRECT: [
    '[data-testid="FlockDirect®-fulfillment-option"]',
  ],
  FLOCK_SELECTOR_CARD_STANDARD: [
    '[data-testid="Standard-fulfillment-option"]',
  ],
};

/** env 优先，再合并 Flock 内置回退 */
export function getFlockSelectorSpecs(envKey: string): string[] {
  const fromEnv = getSelectorSpecs(envKey);
  const fallbacks = FLOCK_BUILTIN_FALLBACKS[envKey] ?? [];
  const seen = new Set<string>();
  const merged: string[] = [];
  for (const spec of [...fromEnv, ...fallbacks]) {
    if (seen.has(spec)) continue;
    seen.add(spec);
    merged.push(spec);
  }
  return merged;
}

export async function fillFlockField(
  page: Page,
  envKey: string,
  value: string,
): Promise<boolean> {
  return fillFirstVisibleFromSpecs(
    page,
    getFlockSelectorSpecs(envKey),
    value,
    { retries: 3 },
  );
}
