/**
 * 本地探：登录态能否打开 /ship 一级表单（用 .env 账密，不依赖 DB）
 *   npx tsx scripts/probe-mothership-open-ship.ts
 *   DIAG_HEADED=true npx tsx scripts/probe-mothership-open-ship.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";

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";

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 main(): Promise<void> {
  // 本地 .env 账密常为空；有 mothership-logged-in-storage 时用 ALS 占位即可走登录态 storage
  let email = process.env.MOTHERSHIP_EMAIL?.trim() ?? "";
  let password = process.env.MOTHERSHIP_PASSWORD?.trim() ?? "";
  const hasStorage = require("node:fs").existsSync(
    ".rpa/mothership-logged-in-storage.json",
  );
  if ((!email || !password) && hasStorage) {
    email = email || "storage-session@local";
    password = password || "storage-session";
    console.log("[probe] .env 账密为空，改用已有 logged-in storage 会话");
  }
  if (!email || !password) {
    console.error("[probe] 缺 MOTHERSHIP_EMAIL / MOTHERSHIP_PASSWORD，且无 logged-in storage");
    process.exit(1);
  }

  const readyDate = readyDatePlusDays(3);
  const req: QuoteRequest = {
    cargoHash: `probe-open-ship-${Date.now()}`,
    pickup: {
      street: "456 Oak Ave",
      city: "Fairhope",
      state: "AL",
      zip: "36532",
      placeId: "probe-pickup",
      formattedAddress: "456 Oak Ave, Fairhope, AL 36532",
      selectedFromSuggestions: true,
      mothershipOptionId: "probe-pickup",
      mothershipDisplayLabel: "456 Oak Ave, Fairhope, AL",
      selectedFromMothership: true,
    },
    delivery: {
      street: "555 Market St",
      city: "San Francisco",
      state: "CA",
      zip: "94105",
      placeId: "probe-delivery",
      formattedAddress: "555 Market St, San Francisco, CA 94105",
      selectedFromSuggestions: true,
      mothershipOptionId: "probe-delivery",
      mothershipDisplayLabel: "555 Market St, San Francisco, CA",
      selectedFromMothership: true,
    },
    weightLb: 250,
    dimsIn: { l: 48, w: 40, h: 48 },
    palletCount: 2,
    cargoType: "general_freight",
    readyDate,
    readyTime: "12:00 PM",
    cargoLines: [
      {
        cargoType: "general_freight",
        quantity: 2,
        weightLb: 250,
        lengthIn: 48,
        widthIn: 40,
        heightIn: 48,
      },
    ],
  };

  console.log("=== probe open /ship (env login) ===");
  console.log(`email=${email.slice(0, 2)}*** headed=${wantHeaded} ready=${readyDate}`);

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

main().catch((e) => {
  console.error("[probe] FAIL", e instanceof Error ? e.message : e);
  process.exit(1);
});
