/**
 * 快速验证 styled-components 联想点击能否触发 GET place
 */
import "dotenv/config";
import { loadDevEnv } from "@/lib/dev-env";
import { getPrimaryMothershipQuoteUrl } from "@/lib/rpa/env";
import {
  hostFetchMothershipCandidates,
} from "@/lib/frontend/api-client";
import { applyMothershipCandidate } from "@/lib/frontend/mothership-address";
import { AxelSelectionBridge } from "@/workers/rpa/axel-selection-bridge";
import { MotherShipAddressAdapter } from "@/workers/rpa/address-adapter/mothership-address-adapter";
import { openAddressSide, visibleStreetInput } from "@/workers/rpa/address-side";
import { RPAContext } from "@/workers/rpa/kernel/context";
import { closeBrowser, openQuotePage } from "@/workers/rpa/session-manager";
import { quotePageAdapter } from "@/workers/rpa/quote-page-adapter";
import {
  stabilizeQuoteLandingPage,
  waitForQuoterWidgetHydrated,
} from "@/workers/rpa/page-prep";
import { getSelector } from "@/lib/rpa/selectors";
import type { QuoteRequest } from "@/modules/providers/quote-provider";

loadDevEnv();

const BASE = process.env.PROVE_BASE_URL ?? "http://localhost:3000";
const TOKEN = "demo-host-token";
const CUSTOMER_ID = "CUST_001";

async function main() {
  const pickupDraft = {
    street: "3131 Western Ave",
    city: "Seattle",
    state: "WA",
    zip: "",
    place_id: "draft_seattle",
    formatted_address: "3131 Western Ave, Seattle, WA",
    selected_from_suggestions: true,
  };
  const deliveryDraft = {
    street: "7000 NW 52nd St",
    city: "Miami",
    state: "FL",
    zip: "",
    place_id: "draft_miami",
    formatted_address: "7000 NW 52nd St, Miami, FL",
    selected_from_suggestions: true,
  };

  const candRes = await hostFetchMothershipCandidates(
    BASE,
    TOKEN,
    CUSTOMER_ID,
    pickupDraft,
    deliveryDraft,
  );
  if (candRes.code !== 0 || !candRes.data?.pickup_candidates[0]) {
    throw new Error(candRes.message ?? "候选 API 失败");
  }
  const pickupCand = candRes.data.pickup_candidates[0];
  const pickupApplied = applyMothershipCandidate(pickupDraft, pickupCand);
  const pickup: QuoteRequest["pickup"] = {
    street: pickupApplied.street,
    city: pickupApplied.city,
    state: pickupApplied.state,
    zip: pickupApplied.zip ?? "",
    placeId: pickupDraft.place_id,
    formattedAddress: pickupApplied.formatted_address,
    selectedFromSuggestions: true,
    mothershipOptionId: pickupApplied.mothership_option_id ?? "",
    mothershipDisplayLabel: pickupApplied.mothership_display_label ?? "",
    selectedFromMothership: true,
  };

  console.log("pickup label:", pickup.mothershipDisplayLabel);
  console.log("MotherShip URL:", getPrimaryMothershipQuoteUrl());

  const opened = await openQuotePage(quotePageAdapter);
  const ctx = RPAContext.fromSession(opened.page, opened.context);
  await stabilizeQuoteLandingPage(ctx);
  await waitForQuoterWidgetHydrated(ctx.page, 60_000);
  await openAddressSide(ctx, "pickup");
  const street = await visibleStreetInput(ctx, "pickup");
  if (!street) throw new Error("无提货输入框");

  const adapter = new MotherShipAddressAdapter();
  const result = await adapter.selectAddress({
    ctx,
    side: "pickup",
    address: pickup,
    street,
    widgetSelector: getSelector("RPA_SELECTOR_QUOTE_WIDGET"),
  });

  const diag = adapter.getDiagnostics();
  console.log("\n=== pickup commit 结果 ===");
  console.log(JSON.stringify({ result, diag }, null, 2));

  const bridge = new AxelSelectionBridge();
  bridge.attach(ctx.page);
  console.log("observed place ids:", bridge.getObservedPlaceCommitIds());

  await ctx.page.screenshot({ path: ".dev/logs/probe-styled-click-pickup.png" });
  await closeBrowser();
}

main().catch((e) => {
  console.error("[FAIL]", e);
  process.exit(1);
});
