import type { MessageWithMeta } from '@/contexts';

/** Returns the user UID for a message, if the sender is a human user */
export function getSenderUserUid(message: MessageWithMeta): string | undefined {
  return message.sender_id ?? undefined;
}

/** Returns the model ID for AI messages.
 *  For AI messages, display_name is the model name; sender_id should be null.
 *  Returns undefined if sender_id looks like a UUID (which would be a user UID, not a model ID). */
export function getSenderModelId(message: MessageWithMeta): string | undefined {
  if (message.sender_type === 'ai') {
    // Use display_name for model identification since sender_id is null for proper AI messages
    if (message.display_name && !looksLikeUuid(message.display_name)) return message.display_name;
    return undefined;
  }
  return undefined;
}

/** Display name for a message sender.
 *  For AI messages, prefers display_name (model name), falls back to 'AI'.
 *  Never returns a raw UUID for AI messages. */
export function getSenderDisplayName(message: MessageWithMeta): string {
  if (message.sender_type === 'ai') {
    if (message.display_name && !looksLikeUuid(message.display_name)) return message.display_name;
    return 'AI';
  }
  if (message.sender_type === 'system') return 'System';
  if (message.sender_type === 'tool') return 'Tool';
  if (message.display_name) return message.display_name;
  return message.sender_type;
}

function looksLikeUuid(s: string): boolean {
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);
}

/** Avatar URL from a MessageWithMeta.
 *  Callers should pass members to resolve the avatar.
 *  This helper returns undefined for now — avatar resolution is done in components
 *  using members.find() for consistency with the rest of the codebase.
 */
export function getAvatarFromUiMessage(_message: MessageWithMeta): string | undefined {
  return undefined;
}

/** Whether the sender is a human user */
export function isUserSender(message: MessageWithMeta): boolean {
  return ['member', 'admin', 'owner', 'guest'].includes(message.sender_type);
}
