/**
 * 诊断：登录态 MotherShip LA→SF 地址查价（有头可视化）
 *   npx tsx scripts/diag-mothership-logged-in-la-sf.ts
 *   DIAG_HEADED=false npx tsx scripts/diag-mothership-logged-in-la-sf.ts
 *
 * 失败时由 runMothershipLoggedInDashboardQuote 在关浏览器前写入 .rpa/diag/
 */
import { loadDevEnv } from "@/lib/dev-env";

loadDevEnv();

const wantHeaded = process.env.DIAG_HEADED !== "false";
process.env.RPA_HEADED = wantHeaded ? "true" : "false";
process.env.RPA_HEADLESS = wantHeaded ? "false" : "true";
if (wantHeaded && !process.env.RPA_SLOW_MO_MS?.trim()) {
  process.env.RPA_SLOW_MO_MS = "80";
}
if (!wantHeaded) {
  delete process.env.RPA_SLOW_MO_MS;
}

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 =
  "2020 West Washington Boulevard floor 5 rm 508, Los Angeles, CA, USA";
const DELIVERY_Q = "555 Market St ste 1001, San Francisco, CA, USA";

/** 今天起 +N 天（避开当天） */
function readyDatePlusDays(daysAhead: number): string {
  const d = new Date();
  d.setDate(d.getDate() + daysAhead);
  const yyyy = d.getFullYear();
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${yyyy}-${mm}-${dd}`;
}

async function pickFirstSelectable(query: string) {
  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 ok q=${query.slice(0, 40)}… option=${hit.option_id.slice(0, 16)} 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 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);
  }

  const readyDate = process.env.DIAG_READY_DATE?.trim() || readyDatePlusDays(3);
  const readyTime = process.env.DIAG_READY_TIME?.trim() || "12:00 PM";

  console.log("=== MotherShip 登录态诊断 LA→SF ===");
  console.log(`customer=${customerId} email=${login.email.slice(0, 2)}***`);
  console.log(
    `headed=${wantHeaded} slowMo=${process.env.RPA_SLOW_MO_MS ?? 0}`,
  );
  console.log(`ready=${readyDate} ${readyTime}`);
  console.log("失败产物在 .rpa/diag/");

  const [pickupC, deliveryC] = await Promise.all([
    pickFirstSelectable(PICKUP_Q),
    pickFirstSelectable(DELIVERY_Q),
  ]);

  const req: QuoteRequest = {
    cargoHash: `diag-la-sf-${Date.now()}`,
    pickup: toAddr(pickupC),
    delivery: toAddr(deliveryC),
    weightLb: 480,
    dimsIn: { l: 48, w: 40, h: 48 },
    palletCount: 2,
    cargoType: "general_freight",
    readyDate,
    readyTime,
    cargoLines: [
      {
        cargoType: "general_freight",
        quantity: 2,
        weightLb: 480,
        lengthIn: 48,
        widthIn: 40,
        heightIn: 48,
      },
    ],
  };

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

  const items = await runWithMothershipLoginContext(login, "customer", () =>
    runMothershipLoggedInDashboardQuote(req),
  );
  console.log(
    `[diag] OK carriers=${items.map((i) => `${i.carrier}=$${i.rawTotal}`).join(", ")}`,
  );
}

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