import { Prisma } from "@prisma/client";
import { QUOTE_VALIDITY_MS } from "@/lib/constants/quote";
import { CAPTCHA_PAUSE_MINUTES } from "@/lib/constants/rpa";
import { prepareMotherShipStorageQuotes } from "@/modules/quote/quote-completeness";
import { detectDeviation } from "@/modules/alert/deviation-detector";
import { writeAlert } from "@/modules/alert/service";
import {
  closeCircuit,
  isCircuitOpen,
  recordRpaFailure,
  recordRpaSuccess,
} from "@/modules/cache/circuit-breaker";
import { overwriteL1, setL2, setL3 } from "@/modules/cache/redis-cache";
import { prisma } from "@/lib/prisma";
import { applyMarkupToQuotes, getMarkupRule } from "@/modules/pricing/engine";
import { getConfidenceScore } from "@/modules/quote/confidence";
import { handleRpaFailure } from "@/modules/quote/fallback-orchestrator";
import type { QuoteJobData } from "@/modules/quote/rpa-queue";
import { NO_RETRY_CODES, RpaError } from "@/modules/rpa/errors";
import { isEntryErrorCode } from "@/modules/rpa/error-mapper";
import {
  cargoToQuoteRequest,
  quoteItemsToRawTiers,
} from "@/modules/rpa/quote-mapper";
import { recordPostDone, safeRecord } from "@/modules/metrics/collector";
import { recordQuoteQueryOutcome } from "@/modules/quote/query-log";
import { mothershipProvider } from "@/workers/rpa/mothership";
import {
  heartbeat,
  isWorkerPaused,
  pauseWorker,
} from "@/workers/rpa/worker-state";
import { getCustomerProviderLogin, hasCustomerProviderCredential } from "@/modules/customer/provider-credentials";
import {
  runWithMothershipLoginContext,
} from "@/lib/rpa/mothership-login-context";

async function writeRpaAlert(
  alertType: "RPA_CAPTCHA" | "STRUCT_CHANGE" | "SESSION_EXPIRED" | "RPA_FAILED",
  quoteId: string,
  cargoHash: string,
  detail: Record<string, unknown>,
): Promise<void> {
  await writeAlert(alertType, { quoteId, cargoHash, detail });
}

async function completeQuoteSuccess(
  data: QuoteJobData,
  rawQuotes: ReturnType<typeof quoteItemsToRawTiers>,
): Promise<void> {
  const uiQuotes = prepareMotherShipStorageQuotes(rawQuotes);
  const markupRule = await getMarkupRule(data.customerId);
  const markedQuotes = applyMarkupToQuotes(uiQuotes, markupRule);
  const validUntil = new Date(Date.now() + QUOTE_VALIDITY_MS);
  const cachePayload = { quotes: uiQuotes };

  await setL2(data.cargoHash, cachePayload);
  await setL3(data.cargoHash, cachePayload);

  await prisma.quoteRecord.update({
    where: { quoteId: data.quoteId },
    data: {
      status: "done",
      sourceType: "rpa",
      isRealtime: true,
      confidenceScore: getConfidenceScore("rpa"),
      markupPercent:
        markupRule.type === "percent" ? markupRule.percent : 0,
      quotesJson: markedQuotes as unknown as Prisma.InputJsonValue,
      validUntil,
      errorCode: null,
    },
  });

  await detectDeviation(data.cargoHash, uiQuotes, data.quoteId);

  const doneResponse = {
    quote_id: data.quoteId,
    status: "done" as const,
    source_type: "rpa" as const,
    is_realtime: true,
  };
  await overwriteL1(data.requestId, {
    quoteId: data.quoteId,
    response: doneResponse,
  });

  await recordQuoteQueryOutcome(data.quoteId, "success", {
    sourceType: "rpa",
    tierCount: markedQuotes.length,
  });
}

/** 单条 RPA job 处理（task-029） */
export async function processQuoteJob(
  data: QuoteJobData,
  workerId: string,
  options?: { isFinalAttempt?: boolean },
): Promise<void> {
  await heartbeat(workerId);

  if (await isCircuitOpen()) {
    throw new RpaError("PAGE_LOAD_TIMEOUT", "RPA 熔断中，暂缓消费", {
      retryable: true,
    });
  }

  if (await isWorkerPaused(workerId)) {
    throw new RpaError("RPA_CAPTCHA", "Worker 已暂停", { retryable: true });
  }

  try {
    const configured = await hasCustomerProviderCredential(
      data.customerId,
      "mothership",
    );
    const customerLogin = await getCustomerProviderLogin(
      data.customerId,
      "mothership",
    );
    if (configured && !customerLogin) {
      throw new RpaError(
        "RPA_DATA_INVALID",
        `MOTHERSHIP_LOGIN_FAILED：客户 ${data.customerId} 已配置 MotherShip 账密但解密失败，请检查 JWT_SECRET 后在管理端重新保存密码（禁止改走匿名 Direct）`,
        { retryable: false },
      );
    }
    const envEmail = process.env.MOTHERSHIP_EMAIL?.trim() ?? "";
    const envPassword = process.env.MOTHERSHIP_PASSWORD?.trim() ?? "";
    const envLogin =
      envEmail && envPassword
        ? { email: envEmail, password: envPassword }
        : null;
    const login = customerLogin ?? envLogin;
    const source = customerLogin ? "customer" : envLogin ? "env" : null;
    if (login) {
      console.log(
        `[rpa] MotherShip 登录凭据 source=${source} customerId=${data.customerId} email=${login.email.slice(0, 2)}***`,
      );
    } else {
      console.log(
        `[rpa] MotherShip 无客户/环境账密 customerId=${data.customerId} → 匿名 Axel Direct`,
      );
    }

    const result = await runWithMothershipLoginContext(login, source, () =>
      mothershipProvider.getQuote(cargoToQuoteRequest(data.cargo)),
    );
    const rawQuotes = quoteItemsToRawTiers(result.items);
    await completeQuoteSuccess(data, rawQuotes);
    safeRecord(() =>
      recordPostDone({
        quoteId: data.quoteId,
        sourceType: "rpa",
        isRealtime: true,
      }),
    );
    await recordRpaSuccess();
    await closeCircuit();
  } catch (error) {
    if (error instanceof RpaError) {
      if (error.pauseWorker) {
        await pauseWorker(workerId, CAPTCHA_PAUSE_MINUTES);
        await writeRpaAlert("RPA_CAPTCHA", data.quoteId, data.cargoHash, {
          worker_id: workerId,
          message: error.message,
        });
      } else if (error.code === "STRUCT_CHANGE") {
        await writeRpaAlert("STRUCT_CHANGE", data.quoteId, data.cargoHash, {
          message: error.message,
        });
      } else if (error.code === "QUOTE_ENTRY_UNAVAILABLE") {
        await writeRpaAlert("RPA_FAILED", data.quoteId, data.cargoHash, {
          message: error.message,
          entry_error: "QUOTE_ENTRY_UNAVAILABLE",
        });
      } else if (error.code === "SESSION_EXPIRED") {
        await writeRpaAlert("SESSION_EXPIRED", data.quoteId, data.cargoHash, {
          message: error.message,
        });
      } else if (error.code === "PROVIDER_LOGIN_FAILED") {
        await writeRpaAlert("RPA_FAILED", data.quoteId, data.cargoHash, {
          message: error.message,
          entry_error: "PROVIDER_LOGIN_FAILED",
        });
      }
    }

    const shouldCountFailure = !(
      error instanceof RpaError &&
      (NO_RETRY_CODES.has(error.code) || isEntryErrorCode(error.code))
    );
    if (shouldCountFailure) {
      await recordRpaFailure();
    }

    const isFinalAttempt = options?.isFinalAttempt ?? true;
    const canRetry =
      error instanceof RpaError &&
      error.retryable &&
      !isEntryErrorCode(error.code) &&
      !isFinalAttempt;

    if (canRetry) {
      throw error;
    }

    await handleRpaFailure(
      data.quoteId,
      data.cargoHash,
      data.customerId,
      error,
    );

    if (error instanceof RpaError && !error.retryable) {
      return;
    }

    throw error;
  }
}
