// Persona resolution helpers — pure, no React.
//
// Resolution cascade for a bubble's persona:
//   1. message.sender              (per-message override; multi-user chats)
//   2. config.user / config.assistant (provider-level default)
//   3. role-based fallback         ('You' / 'AI')

import type { ChatAssistantContext, ChatMessage, ChatPersona, ChatUserContext } from '../types';

const FALLBACK_USER: ChatPersona = { name: 'You', initials: 'You' };
const FALLBACK_ASSISTANT: ChatPersona = { name: 'AI', initials: 'AI' };

export function resolvePersona(
  message: Pick<ChatMessage, 'role' | 'sender'>,
  user?: ChatUserContext,
  assistant?: ChatAssistantContext,
): ChatPersona {
  if (message.sender) return message.sender;
  if (message.role === 'user') return user ?? FALLBACK_USER;
  if (message.role === 'assistant') return assistant ?? FALLBACK_ASSISTANT;
  return { name: message.role };
}

/** Compute initials for an avatar fallback. */
export function deriveInitials(persona: ChatPersona, role?: string): string {
  if (persona.initials) return persona.initials;
  if (persona.name) {
    const parts = persona.name.trim().split(/\s+/);
    if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  }
  if (role === 'user') return 'You';
  if (role === 'assistant') return 'AI';
  return '?';
}
