/**
 * Priority1 公开询价 RPA — 供 worker 与脚本共用
 */
import { runPriority1VisualChain } from "@/workers/rpa/priority1/visual-chain";
import {
  formatExternalSiteNavigationError,
  isTransientNavigationError,
} from "@/lib/rpa/page-goto";
import type { Priority1DemoInput } from "@/workers/rpa/priority1/demo-input";
import type {
  Priority1QuoteLine,
  Priority1QuoteOutcome,
} from "@/workers/rpa/priority1/quote-extract";
import { PRIORITY1_MANUAL_FOLLOWUP_MESSAGE } from "@/workers/rpa/priority1/quote-extract";

export type Priority1RunQuoteResult = {
  quotes: Priority1QuoteLine[];
  ok: boolean;
  quoteOutcome?: Priority1QuoteOutcome;
  message?: string;
  errorMessage?: string;
};

function mockPriority1Quotes(): Priority1QuoteLine[] {
  return [
    {
      rank: 1,
      carrier: "Mock Carrier A",
      carrierCode: "MCA",
      totalUsd: 428.5,
      transitDays: 3,
      deliveryDate: null,
      expirationDate: null,
      serviceLevel: "Standard",
      quoteId: null,
      caboUrl: null,
      source: "visible-dom",
    },
    {
      rank: 2,
      carrier: "Mock Carrier B",
      carrierCode: "MCB",
      totalUsd: 512.0,
      transitDays: 2,
      deliveryDate: null,
      expirationDate: null,
      serviceLevel: "Standard",
      quoteId: null,
      caboUrl: null,
      source: "visible-dom",
    },
  ];
}

async function runProductionPriority1Rpa(
  input: Priority1DemoInput,
): Promise<Priority1RunQuoteResult> {
  if (process.env.RPA_DWELL_MS == null) {
    process.env.RPA_DWELL_MS = "0";
  }
  if (process.env.RPA_SLOW_MO_MS == null) {
    process.env.RPA_SLOW_MO_MS = "0";
  }
  if (process.env.RPA_QUOTE_POLL_MS == null) {
    process.env.RPA_QUOTE_POLL_MS = "600";
  }

  const result = await runPriority1VisualChain({
    demo: input,
    caseId: `worker-${Date.now()}`,
    workerFast: true,
  });

  if (!result.ok) {
    const raw = result.error ?? "Priority1 RPA 执行失败";
    return {
      quotes: [],
      ok: false,
      quoteOutcome: result.quoteOutcome ?? "no_result",
      errorMessage: isTransientNavigationError({ message: raw })
        ? formatExternalSiteNavigationError("Priority1 官网", { message: raw })
        : raw,
    };
  }

  if (result.quoteOutcome === "manual_followup") {
    return {
      quotes: [],
      ok: true,
      quoteOutcome: "manual_followup",
      message: result.message ?? PRIORITY1_MANUAL_FOLLOWUP_MESSAGE,
    };
  }

  if (result.quotes.length > 0) {
    return {
      quotes: result.quotes,
      ok: true,
      quoteOutcome: "instant_quote",
    };
  }

  return {
    quotes: [],
    ok: false,
    quoteOutcome: result.quoteOutcome ?? "no_result",
    errorMessage: result.error ?? "Priority1 报价提取失败",
  };
}

/** 按用户模拟参数在 Priority1 官网真实填表并抓取报价 */
export async function runPriority1QuoteRpa(
  input: Priority1DemoInput,
): Promise<Priority1RunQuoteResult> {
  if (process.env.RPA_MOCK_MODE === "true") {
    return {
      quotes: mockPriority1Quotes(),
      ok: true,
      quoteOutcome: "instant_quote",
    };
  }

  return runProductionPriority1Rpa(input);
}
