import type { Page } from "playwright";
import type { AxelSelectionBridge } from "@/workers/rpa/axel-selection-bridge";
import { fetchAxelPlaceLocation } from "@/workers/rpa/axel-place-prefetch";
import { INVOKE_CAPTURED_PLACE_CHANGED } from "@/workers/rpa/fix-place/browser-eval-scripts";

const COMMIT_TIMEOUT_MS = 10_000;

/**
 * 直接调用 initScript 捕获的 place_changed handler（绕过 event.trigger / DOM 点击）。
 */
export async function commitViaDirectPlaceChangedListener(
  page: Page,
  bridge: AxelSelectionBridge,
  placeId: string,
  description: string,
): Promise<{ ok: boolean; method: string }> {
  const fetched = await fetchAxelPlaceLocation(page, placeId);
  if (!fetched.ok || !fetched.location) {
    console.log(
      `[rpa] direct-listener: GET place 失败 status=${fetched.status}`,
    );
    return { ok: false, method: "direct-listener-prefetch-failed" };
  }

  bridge.setPlaceDetails(placeId, fetched.location);

  const result = (await page.evaluate(INVOKE_CAPTURED_PLACE_CHANGED, {
    pid: placeId,
    desc: description,
    loc: fetched.location,
  })) as { ok: boolean; reason?: string; handlerCount?: number };

  if (!result?.ok) {
    console.log(
      `[rpa] direct-listener: 调用失败 reason=${result?.reason ?? "unknown"} handlers=${result?.handlerCount ?? 0}`,
    );
    return { ok: false, method: "direct-listener-invoke-failed" };
  }

  const committed = await bridge.waitForPlaceCommit(placeId, COMMIT_TIMEOUT_MS);
  if (committed) {
    console.log("[rpa] direct-listener: place_changed handler 触发 place 200");
    return { ok: true, method: "direct-place-changed-listener" };
  }

  console.log(
    "[rpa] direct-listener: handler 已调用但无 place 200（可能非 Google 路径）",
  );
  return { ok: false, method: "direct-listener-no-network" };
}
