/**
 * 计时诊断：Brea CA → Fairhope AL
 *   DIAG_HEADED=false npx tsx scripts/diag-mothership-timing-brea-fairhope.ts
 */
import { loadDevEnv } from "@/lib/dev-env";

loadDevEnv();

const wantHeaded = process.env.DIAG_HEADED === "true";
process.env.RPA_HEADED = wantHeaded ? "true" : "false";
process.env.RPA_HEADLESS = wantHeaded ? "false" : "true";
if (!wantHeaded) delete process.env.RPA_SLOW_MO_MS;
else if (!process.env.RPA_SLOW_MO_MS?.trim()) process.env.RPA_SLOW_MO_MS = "0";

import { resolveAxelMothershipSuggest } from "@/lib/axel/candidates";
import { runWithMothershipLoginContext } from "@/lib/rpa/mothership-login-context";
import { getCustomerProviderLogin } from "@/modules/customer/provider-credentials";
import type { QuoteRequest } from "@/modules/providers/quote-provider";
import {
  buildLoggedInAddressSearchQuery,
  runMothershipLoggedInDashboardQuote,
} from "@/workers/rpa/mothership-logged-in-quote";

const PICKUP_Q = "789 East Elm Street suite 301, Brea, CA, USA";
const DELIVERY_Q = "456 Oak Avenue unit 207, Fairhope, AL, USA";
const READY_DATE = process.env.DIAG_READY_DATE?.trim() || "2026-07-20";
const READY_TIME = process.env.DIAG_READY_TIME?.trim() || "12:00 PM";

async function pickFirstSelectable(query: string) {
  const t0 = Date.now();
  const list = await resolveAxelMothershipSuggest(query);
  const hit = list.find((c) => c.selectable !== false && c.option_id.trim());
  if (!hit) throw new Error(`MotherShip 无可用联想: ${query.slice(0, 60)}`);
  console.log(
    `[diag] suggest ms=${Date.now() - t0} q=${query.slice(0, 48)} street=${hit.street} city=${hit.city}`,
  );
  return hit;
}

function toAddr(c: Awaited<ReturnType<typeof pickFirstSelectable>>) {
  return {
    street: c.street,
    city: c.city,
    state: c.state,
    zip: c.zip || "",
    placeId: c.option_id,
    formattedAddress: c.formatted_address || c.display_label,
    selectedFromSuggestions: true,
    mothershipOptionId: c.option_id,
    mothershipDisplayLabel: c.display_label,
    selectedFromMothership: true,
  };
}

async function main(): Promise<void> {
  const wall0 = Date.now();
  const customerId = process.env.DIAG_CUSTOMER_ID?.trim() || "CUST_001";
  const login = await getCustomerProviderLogin(customerId, "mothership");
  if (!login) {
    console.error(`[diag] 无 MotherShip 账密 customer=${customerId}`);
    process.exit(1);
  }

  console.log("=== MotherShip 计时诊断 Brea→Fairhope ===");
  console.log(`customer=${customerId} headed=${wantHeaded}`);
  console.log(`ready=${READY_DATE} ${READY_TIME}`);
  console.log("cargo=Pallet qty=2 wt=250 dims=60x50x60");

  const suggest0 = Date.now();
  const [pickupC, deliveryC] = await Promise.all([
    pickFirstSelectable(PICKUP_Q),
    pickFirstSelectable(DELIVERY_Q),
  ]);
  console.log(`[diag] suggest-total ms=${Date.now() - suggest0}`);

  const req: QuoteRequest = {
    cargoHash: `diag-brea-fairhope-${Date.now()}`,
    pickup: toAddr(pickupC),
    delivery: toAddr(deliveryC),
    weightLb: 250,
    dimsIn: { l: 60, w: 50, h: 60 },
    palletCount: 2,
    cargoType: "general_freight",
    readyDate: READY_DATE,
    readyTime: READY_TIME,
    cargoLines: [
      {
        cargoType: "general_freight",
        quantity: 2,
        weightLb: 250,
        lengthIn: 60,
        widthIn: 50,
        heightIn: 60,
      },
    ],
  };

  console.log(
    `[diag] RPA search pickup=${buildLoggedInAddressSearchQuery(req.pickup)}`,
  );
  console.log(
    `[diag] RPA search delivery=${buildLoggedInAddressSearchQuery(req.delivery)}`,
  );

  const rpa0 = Date.now();
  const items = await runWithMothershipLoginContext(login, "customer", () =>
    runMothershipLoggedInDashboardQuote(req),
  );
  const rpaMs = Date.now() - rpa0;
  const wallMs = Date.now() - wall0;

  console.log(
    `[diag] OK rpaMs=${rpaMs} wallMs=${wallMs} carriers=${items
      .map((i) => `${i.carrier}=$${i.rawTotal}`)
      .join(", ")}`,
  );
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
