/** 阶段0录证专用环境解析（独立于 workers/rpa） */

const FORBIDDEN_QUOTE_URL_PATTERNS: RegExp[] = [
  /dashboard\.mothership\.com/i,
  /www\.mothership\.com\/quote/i,
];

export function parseQuoteUrls(raw: string | undefined): string[] {
  if (!raw?.trim()) {
    return [];
  }
  return raw
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean);
}

export function isForbiddenQuoteUrl(url: string): boolean {
  return FORBIDDEN_QUOTE_URL_PATTERNS.some((pattern) => pattern.test(url));
}

export function resolveEntryUrl(): string {
  const urls = parseQuoteUrls(process.env.MOTHERSHIP_QUOTE_URLS);
  const first = urls[0];
  if (!first) {
    throw new Error(
      "MOTHERSHIP_QUOTE_URLS 未配置。请在 .env 中设置 headed 录制验证的匿名入口 URL。",
    );
  }
  if (isForbiddenQuoteUrl(first)) {
    throw new Error(`禁止的报价入口 URL（GD-15）: ${first}`);
  }
  try {
    new URL(first);
  } catch {
    throw new Error(`无效的报价入口 URL: ${first}`);
  }
  return first;
}

export function resolveBrowserChannel(): string | undefined {
  const channel = process.env.RPA_BROWSER_CHANNEL?.trim();
  return channel || undefined;
}
