/**
 * 本地复现：截图同款地址 + 可选预约附加服务
 *   npx tsx scripts/probe-ms-logged-in-salem-sancarlos.ts
 *   PROBE_APPOINTMENT=1 npx tsx scripts/probe-ms-logged-in-salem-sancarlos.ts
 */
import { loadDevEnv } from "@/lib/dev-env";

loadDevEnv();

process.env.RPA_HEADED = process.env.DIAG_HEADED === "true" ? "true" : "false";
process.env.RPA_HEADLESS = process.env.DIAG_HEADED === "true" ? "false" : "true";

import fs from "node:fs";
import { runWithMothershipLoginContext } from "@/lib/rpa/mothership-login-context";
import type { QuoteRequest } from "@/modules/providers/quote-provider";
import { runMothershipLoggedInDashboardQuote } from "@/workers/rpa/mothership-logged-in-quote";
import { RpaError } from "@/modules/rpa/errors";

function nextWeekdayIso(daysAhead = 2): string {
  const d = new Date();
  d.setDate(d.getDate() + daysAhead);
  while (d.getDay() === 0 || d.getDay() === 6) {
    d.setDate(d.getDate() + 1);
  }
  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 main(): Promise<void> {
  let email = process.env.MOTHERSHIP_EMAIL?.trim() ?? "";
  let password = process.env.MOTHERSHIP_PASSWORD?.trim() ?? "";
  const hasStorage = fs.existsSync(".rpa/mothership-logged-in-storage.json");
  if ((!email || !password) && hasStorage) {
    email = email || "storage-session@local";
    password = password || "storage-session";
    console.log("[probe] 使用 logged-in storage 会话");
  }
  if (!email || !password) {
    console.error("[probe] 缺账密且无 storage");
    process.exit(1);
  }

  const withAppointment = process.env.PROBE_APPOINTMENT === "1";
  const readyDate = nextWeekdayIso(2);

  const req: QuoteRequest = {
    cargoHash: `probe-salem-sc-${Date.now()}`,
    pickup: {
      street: "888 Liberty Street Northeast",
      city: "Salem",
      state: "OR",
      zip: "97301",
      placeId: "probe-salem",
      formattedAddress: "888 Liberty Street Northeast unit d 3, Salem, OR, USA",
      selectedFromSuggestions: true,
      mothershipOptionId: "probe-salem",
      mothershipDisplayLabel: "888 Liberty Street Northeast unit d 3, Salem, OR, USA",
      selectedFromMothership: true,
    },
    delivery: {
      street: "789 Elm Street",
      city: "San Carlos",
      state: "CA",
      zip: "94070",
      placeId: "probe-sancarlos",
      formattedAddress: "789 Elm Street suite 301, San Carlos, CA, USA",
      selectedFromSuggestions: true,
      mothershipOptionId: "probe-sancarlos",
      mothershipDisplayLabel: "789 Elm Street suite 301, San Carlos, CA, USA",
      selectedFromMothership: true,
    },
    weightLb: 500,
    dimsIn: { l: 48, w: 40, h: 48 },
    palletCount: 1,
    cargoType: "general_freight",
    readyDate,
    readyTime: "11:00 AM",
    deliveryAccessorials: withAppointment ? ["appointment"] : [],
    cargoLines: [
      {
        cargoType: "pallet",
        quantity: 1,
        weightLb: 500,
        lengthIn: 48,
        widthIn: 40,
        heightIn: 48,
      },
    ],
  };

  console.log(
    `=== Salem OR → San Carlos CA appointment=${withAppointment} ready=${readyDate} ===`,
  );

  try {
    const items = await runWithMothershipLoginContext(
      { email, password },
      "env",
      () => runMothershipLoggedInDashboardQuote(req),
    );
    console.log(
      `[probe] OK n=${items.length} ${items.map((i) => `${i.carrier}=$${i.rawTotal}`).join(" | ")}`,
    );
  } catch (e) {
    if (e instanceof RpaError) {
      console.error(`[probe] FAIL code=${e.code} msg=${e.message}`);
    } else {
      console.error("[probe] FAIL", e instanceof Error ? e.message : e);
    }
    process.exit(1);
  }
}

main();
