import { ensureArray } from "@/workers/rpa/kernel/context-validator";
import type {
  CargoStateEvidence,
  CargoStateProbe,
} from "@/workers/rpa/kernel/state-engine";

const EMPTY_CARGO_EVIDENCE: CargoStateEvidence = {
  phase: "no_cargo_inputs",
  mountedCargoFields: [],
  interactiveCargoFields: [],
  blockedCargoFields: [],
};

/** browser evaluate 结果归一化，禁止 undefined 流入 state */
export function normalizeCargoEvidence(
  raw: CargoStateEvidence | null | undefined,
): CargoStateEvidence {
  if (!raw || typeof raw !== "object") {
    return EMPTY_CARGO_EVIDENCE;
  }
  return {
    phase: raw.phase ?? "no_cargo_inputs",
    mountedCargoFields: ensureArray(raw.mountedCargoFields),
    interactiveCargoFields: ensureArray(raw.interactiveCargoFields),
    blockedCargoFields: ensureArray(raw.blockedCargoFields),
  };
}

export function buildCargoProbe(
  raw: CargoStateEvidence | null | undefined,
  isReady: (evidence: CargoStateEvidence) => boolean,
): CargoStateProbe {
  const evidence = normalizeCargoEvidence(raw);
  return { ready: isReady(evidence), evidence };
}
