#!/usr/bin/env tsx
/**
 * 有头可视化：FTL 另外两种 Select Trailer Type（Open Deck / Temperature Controlled）
 * 填写计划以 form-logic-map.ts 为准；仅观测 Step 2，不等待报价。
 *
 *   npm run visual:priority1-inspect-ftl-trailers
 */
process.env.RPA_HEADLESS = "false";
process.env.RPA_KEEP_BROWSER_OPEN = "true";
process.env.RPA_SLOW_MO_MS = "200";
process.env.RPA_DWELL_MS = "3500";

import { mkdirSync } from "node:fs";
import { join } from "node:path";
import {
  DEFAULT_FTL_OPEN_DECK_DEMO,
  DEFAULT_FTL_TEMP_DEMO,
  formatPriority1InputSummary,
} from "@/workers/rpa/priority1/demo-input";
import { buildPriority1FormPlan } from "@/workers/rpa/priority1/form-logic-map";
import { FTL_TRAILER } from "@/workers/rpa/priority1/shipment-types";

const outRoot = join(process.cwd(), ".rpa", "visual-priority1-inspect");

const RUNS = [
  {
    demo: DEFAULT_FTL_OPEN_DECK_DEMO,
    caseId: "ftl-open-deck-inspect",
    trailerLabel: FTL_TRAILER.open_deck.label,
  },
  {
    demo: DEFAULT_FTL_TEMP_DEMO,
    caseId: "ftl-temp-inspect",
    trailerLabel: FTL_TRAILER.temperature_controlled.label,
  },
] as const;

async function main(): Promise<void> {
  const { runPriority1VisualChain } = await import("./visual-priority1-full-chain");
  mkdirSync(outRoot, { recursive: true });

  console.log("\n[inspect-trailers] FTL Select Trailer Type — Open Deck → Temperature Controlled");
  console.log("[inspect-trailers] 参考 form-logic-map.ts；Step 2 完成后停留 3.5s\n");

  for (let i = 0; i < RUNS.length; i += 1) {
    const run = RUNS[i]!;
    console.log(`\n${"═".repeat(60)}`);
    console.log(`[inspect-trailers] ▶ ${run.trailerLabel}`);
    console.log("─".repeat(60));
    console.log(formatPriority1InputSummary(run.demo));
    console.log("─".repeat(60));
    console.log("[form-logic-map] 展开计划：");
    for (const row of buildPriority1FormPlan(run.demo).filter((p) => p.step === "step2")) {
      console.log(`  ${row.order}. ${row.field.label} ← ${row.value}`);
    }
    console.log("─".repeat(60));

    const result = await runPriority1VisualChain({
      demo: run.demo,
      caseId: run.caseId,
      outDir: join(outRoot, run.caseId),
      keepBrowserOpen: i === RUNS.length - 1,
      stopAfterStep2: true,
    });

    if (!result.ok) {
      console.error(`[inspect-trailers] ${run.caseId} 失败: ${result.error}`);
      process.exit(1);
    }

    if (i < RUNS.length - 1) {
      console.log(
        `\n[inspect-trailers] ${run.trailerLabel} 已完成。Ctrl+C 关闭浏览器后继续下一种…\n`,
      );
    }
  }

  console.log("\n[inspect-trailers] Open Deck 与 Temperature Controlled 均已跑完。");
  console.log(`[inspect-trailers] 截图: ${outRoot}`);
}

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