import type { PortalUser } from '../types';

function isInternalWechatUsername(value?: string | null): boolean {
  return /^wx_[a-z0-9_]{4,64}$/i.test(String(value ?? '').trim());
}

export function resolveUserAddressName(
  user?: Pick<PortalUser, 'displayName' | 'username'> | null,
): string {
  const preferred = user?.displayName?.trim();
  if (preferred) return preferred;
  const username = user?.username?.trim();
  if (username && !isInternalWechatUsername(username)) return username;
  return '用户';
}

/** Hidden agent prefix so replies greet the user by name, not "TKMind". */
export function buildUserAddressPrefix(
  user?: Pick<PortalUser, 'displayName' | 'username'> | null,
): string {
  const name = resolveUserAddressName(user);
  return `[用户身份]
- 当前登录用户称呼：${name}
- 你是 TKMind 助手；与用户对话时用「${name}」称呼对方（如「${name}，你好」），禁止把用户叫作 TKMind。

`;
}

/** Strip hidden user-identity prefix when UI falls back to agent-side content. */
export function stripUserAddressPrefix(text: string): string {
  if (!text.startsWith('[用户身份]\n')) return text;
  const separator = '\n\n';
  const end = text.indexOf(separator);
  if (end === -1) return text;
  return text.slice(end + separator.length).trim();
}
