import type { Locator, Page } from "playwright";
import { pageLocator } from "@/lib/rpa/locator";
import { getSelectorSpecs } from "@/lib/rpa/selector-specs";
import {
  getSelector,
  type RpaSelectorKey,
} from "@/lib/rpa/selectors";
import { ensureArray } from "@/workers/rpa/kernel/context-validator";

/** 所有 selector 访问的唯一入口 */
export class SelectorGraph {
  resolve(key: RpaSelectorKey): string {
    return getSelector(key);
  }

  specs(envKey: string): string[] {
    return ensureArray(getSelectorSpecs(envKey));
  }

  locator(page: Page, key: RpaSelectorKey): Locator {
    return pageLocator(page, this.resolve(key));
  }

  widget(page: Page): Locator {
    return this.locator(page, "RPA_SELECTOR_QUOTE_WIDGET").first();
  }

  optionalEnv(key: string): string | undefined {
    const value = process.env[key]?.trim();
    return value || undefined;
  }
}
