/**
 * 多车道无头复验登录态 MotherShip 查价
 *   DIAG_HEADED=false npx tsx scripts/diag-mothership-logged-in-multi.ts
 */
import { loadDevEnv } from "@/lib/dev-env";

loadDevEnv();

process.env.RPA_HEADED = "false";
process.env.RPA_HEADLESS = "true";
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 LANES: Array<{ name: string; pickup: string; delivery: string }> = [
  {
    name: "LA→SF",
    pickup:
      "2020 West Washington Boulevard floor 5 rm 508, Los Angeles, CA, USA",
    delivery: "555 Market St ste 1001, San Francisco, CA, USA",
  },
  {
    name: "MA→OR",
    pickup: "789 Elm Street, East Bridgewater, MA, USA",
    delivery: "888 Liberty Street Northeast, Salem, OR, USA",
  },
  {
    name: "Dallas→Chicago",
    pickup: "1234 Main Street, Dallas, TX, USA",
    delivery: "200 East Randolph Street, Chicago, IL, USA",
  },
];

async function pickFirst(query: string) {
  const list = await resolveAxelMothershipSuggest(query);
  const hit = list.find((c) => c.selectable !== false && c.option_id.trim());
  if (!hit) throw new Error(`无联想: ${query.slice(0, 50)}`);
  return hit;
}

function toAddr(c: Awaited<ReturnType<typeof pickFirst>>) {
  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 runLane(
  login: { email: string; password: string },
  lane: (typeof LANES)[number],
): Promise<void> {
  const [p, d] = await Promise.all([
    pickFirst(lane.pickup),
    pickFirst(lane.delivery),
  ]);
  const req: QuoteRequest = {
    cargoHash: `multi-${lane.name}-${Date.now()}`,
    pickup: toAddr(p),
    delivery: toAddr(d),
    weightLb: 500,
    dimsIn: { l: 48, w: 40, h: 48 },
    palletCount: 2,
    cargoType: "general_freight",
    cargoLines: [
      {
        cargoType: "general_freight",
        quantity: 2,
        weightLb: 500,
        lengthIn: 48,
        widthIn: 40,
        heightIn: 48,
      },
    ],
  };
  console.log(
    `\n=== ${lane.name} ===\npickup=${buildLoggedInAddressSearchQuery(req.pickup)}\ndelivery=${buildLoggedInAddressSearchQuery(req.delivery)}`,
  );
  const items = await runWithMothershipLoginContext(login, "customer", () =>
    runMothershipLoggedInDashboardQuote(req),
  );
  console.log(
    `[OK] ${lane.name} → ${items.map((i) => `${i.carrier}=$${i.rawTotal}`).join(", ")}`,
  );
}

async function main(): Promise<void> {
  const login = await getCustomerProviderLogin("CUST_001", "mothership");
  if (!login) {
    console.error("无 MotherShip 账密");
    process.exit(1);
  }
  const fails: string[] = [];
  for (const lane of LANES) {
    try {
      await runLane(login, lane);
    } catch (e) {
      const msg = e instanceof Error ? e.message : String(e);
      console.error(`[FAIL] ${lane.name}: ${msg.slice(0, 300)}`);
      fails.push(lane.name);
    }
  }
  if (fails.length) {
    console.error(`\n失败车道: ${fails.join(", ")}`);
    process.exit(1);
  }
  console.log("\n全部车道通过");
}

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