import type { ChatMessage, Profile } from '../types'
import { getTranslatedContent as getTranslation } from '../lib/util'

// Profile info for authors
export interface AuthorInfo {
  did: string
  handle: string
  avatarUrl?: string
}

// Chat collection entry for unified list
export interface ChatCollectionEntry {
  collection: string
  messages: ChatMessage[]
}

// Handle/DID resolver: maps both handle and DID to DID
let handleToDidMap = new Map<string, string>()

export function resolveAuthorDid(authority: string): string {
  return handleToDidMap.get(authority) || authority
}

// Build author info map
export function buildAuthorMap(
  userDid: string,
  userHandle: string,
  botDid: string,
  botHandle: string,
  userProfile?: Profile | null,
  botProfile?: Profile | null,
  pds?: string
): Map<string, AuthorInfo> {
  // Build handle→DID mapping
  handleToDidMap = new Map<string, string>()
  handleToDidMap.set(userHandle, userDid)
  handleToDidMap.set(userDid, userDid)
  handleToDidMap.set(botHandle, botDid)
  handleToDidMap.set(botDid, botDid)

  const authors = new Map<string, AuthorInfo>()

  // User info
  let userAvatarUrl = ''
  if (userProfile?.value.avatar) {
    const cid = userProfile.value.avatar.ref.$link
    userAvatarUrl = pds ? `${pds}/xrpc/com.atproto.sync.getBlob?did=${userDid}&cid=${cid}` : `/at/${userDid}/blob/${cid}`
  }
  authors.set(userDid, { did: userDid, handle: userHandle, avatarUrl: userAvatarUrl })

  // Bot info
  let botAvatarUrl = ''
  if (botProfile?.value.avatar) {
    const cid = botProfile.value.avatar.ref.$link
    botAvatarUrl = pds ? `${pds}/xrpc/com.atproto.sync.getBlob?did=${botDid}&cid=${cid}` : `/at/${botDid}/blob/${cid}`
  }
  authors.set(botDid, { did: botDid, handle: botHandle, avatarUrl: botAvatarUrl })

  return authors
}

// Map collection name to chat type slug
export function chatTypeSlug(chatCollection: string): string {
  if (chatCollection === 'ai.syui.ue.chat') return 'ue'
  return 'log'
}

// Get translated content for a chat message
export function getTranslatedContent(msg: ChatMessage): string {
  const originalLang = msg.value.langs?.[0] || 'ja'
  return getTranslation(msg.value.content.text, msg.value.translations, originalLang)
}

// Re-export from split modules
export { renderChatThreadList, renderChatListPage } from './chat-list'
export { renderChatThread, renderChatThreadPage, renderChatEditForm } from './chat-thread'
