import type { Browser, BrowserContext, BrowserContextOptions } from "playwright";
import { getRpaBrowserLocale } from "@/lib/rpa/env";

export type RpaProxyConfig = {
  server: string;
  username?: string;
  password?: string;
};

/** 从环境变量读取 Playwright HTTP 代理（内网服务器访问美国站时常用） */
export function readRpaProxyConfig(): RpaProxyConfig | undefined {
  const server = process.env.RPA_PROXY_SERVER?.trim();
  if (!server) {
    return undefined;
  }
  const username = process.env.RPA_PROXY_USERNAME?.trim();
  const password = process.env.RPA_PROXY_PASSWORD?.trim();
  return {
    server,
    ...(username ? { username } : {}),
    ...(password ? { password } : {}),
  };
}

/** 创建 RPA 浏览器上下文（locale + 可选代理） */
export async function createRpaBrowserContext(
  browser: Browser,
  overrides?: BrowserContextOptions,
): Promise<BrowserContext> {
  const proxy = readRpaProxyConfig();
  if (proxy) {
    console.log(`[browser-context] 使用代理: ${proxy.server}`);
  }
  return browser.newContext({
    viewport: { width: 1400, height: 900 },
    locale: getRpaBrowserLocale(),
    ...(proxy ? { proxy } : {}),
    ...overrides,
  });
}
