import type { Locator } from "playwright";
import type { QuoteRequest } from "@/modules/providers/quote-provider";
import type { RPAContext } from "@/workers/rpa/kernel/context";

import type { SelectionTraceSnapshot } from "@/workers/rpa/selection-trace";

export type AddressCommitState =
  | "EMPTY"
  | "TYPING"
  | "SUGGESTIONS_READY"
  | "SELECTING"
  | "PLACE_LOADING"
  | "COMMITTED"
  | "FAILED";

export type AddressSelectStatus =
  | "ok"
  | "selection_failed"
  | "no_place_request"
  | "place_http_error"
  | "place_id_mismatch"
  | "timeout";

export type AddressCommitResult = {
  success: boolean;
  placeId: string;
  formattedAddress: string;
  committed: boolean;
};

export type AddressSelectDiagnostics = {
  address: string;
  placeId: string;
  method: string;
  events: string[];
  placeRequestObserved: boolean;
  status: AddressSelectStatus;
  commitState: AddressCommitState;
  /** 取证：候选焦点 / combobox / pac 快照（不改交互） */
  selectionTraces?: SelectionTraceSnapshot[];
  /** 双地址：填 delivery 后 pickup place 是否丢失 */
  pickupLostAfterDelivery?: boolean;
  /** 取证：place 网络事件 */
  placeNetworkEvents?: Array<{
    placeId: string;
    status: number;
    url: string;
    at: number;
  }>;
};

export type SelectAddressParams = {
  ctx: RPAContext;
  side: "pickup" | "delivery";
  address: QuoteRequest["pickup"];
  street: Locator;
  widgetSelector: string;
  pickupAnchor?: QuoteRequest["pickup"];
};

export interface AddressAdapter {
  selectAddress(params: SelectAddressParams): Promise<AddressCommitResult>;
  waitForCommit(): Promise<AddressCommitResult>;
  getCommittedAddress(): AddressCommitResult | null;
  getDiagnostics(): AddressSelectDiagnostics;
  getCommitState(): AddressCommitState;
}
