const MAX_CONVERSATIONS = 20

function getCurrentUser() {
  if (typeof window !== 'undefined' && window.__AIPRO_USER__) return window.__AIPRO_USER__
  return null
}

function normalizeIdentityPart(value) {
  return String(value || '').trim().toLowerCase()
}

function getUserStorageSegment(user) {
  const u = user || getCurrentUser() || {}
  const raw = [
    normalizeIdentityPart(u.email),
    normalizeIdentityPart(u.phone),
    normalizeIdentityPart(u.id),
  ].filter(Boolean).join('|') || 'anonymous'
  return encodeURIComponent(raw)
}

export function getStorageKey(type, user = null) {
  return `chat_conversations_${type}_${getUserStorageSegment(user)}`
}

function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
}

/**
 * 获取某类型的所有历史会话列表（按时间倒序）
 * @param {'create'|'eval'|'sandbox'} type
 * @returns {Array<{id, skillName, preview, updatedAt, messages, sessionId?}>}
 */
export function getConversations(type, user = null) {
  try {
    const raw = localStorage.getItem(getStorageKey(type, user))
    if (!raw) return []
    const list = JSON.parse(raw)
    return list.sort((a, b) => b.updatedAt - a.updatedAt)
  } catch {
    return []
  }
}

/**
 * 保存/更新一条会话
 * @param {'create'|'eval'|'sandbox'} type
 * @param {{id?, skillId?, skillName?, messages, sessionId?}} data
 * @returns {string} 会话 id
 */
export function saveConversation(type, data, user = null) {
  const list = getConversations(type, user)
  const id = data.id || generateId()

  // 生成摘要：取最后一条用户消息的前 40 字
  const lastUserMsg = [...(data.messages || [])].reverse().find(m => m.role === 'user')
  const preview = lastUserMsg ? lastUserMsg.content?.slice(0, 40) || '' : ''

  const existIdx = list.findIndex(c => c.id === id)
  const existing = existIdx >= 0 ? list[existIdx] : null
  const record = {
    ...(existing || {}),
    id,
    skillId: data.skillId || existing?.skillId || null,
    skillName: data.skillName || existing?.skillName || '新对话',
    preview,
    updatedAt: Date.now(),
    messages: data.messages || [],
    sessionId: data.sessionId || existing?.sessionId || null,
  }

  if (existIdx >= 0) {
    list[existIdx] = record
  } else {
    list.unshift(record)
  }

  // 保留最近 N 条
  const trimmed = list.slice(0, MAX_CONVERSATIONS)

  try {
    localStorage.setItem(getStorageKey(type, user), JSON.stringify(trimmed))
  } catch {
    // localStorage 满了，清掉最旧的一半再试
    const half = trimmed.slice(0, Math.floor(MAX_CONVERSATIONS / 2))
    localStorage.setItem(getStorageKey(type, user), JSON.stringify(half))
  }

  return id
}

/**
 * 加载某条会话
 * @param {'create'|'eval'|'sandbox'} type
 * @param {string} id
 * @returns {object|null}
 */
export function loadConversation(type, id, user = null) {
  const list = getConversations(type, user)
  return list.find(c => c.id === id) || null
}

/**
 * 删除某条会话
 * @param {'create'|'eval'|'sandbox'} type
 * @param {string} id
 */
export function deleteConversation(type, id, user = null) {
  const list = getConversations(type, user)
  const filtered = list.filter(c => c.id !== id)
  localStorage.setItem(getStorageKey(type, user), JSON.stringify(filtered))
}

function normalizeSearch(value) {
  return String(value || '').toLowerCase().replace(/\s+/g, '')
}

function isSubsequence(needle, haystack) {
  if (!needle) return true
  let pos = 0
  for (const ch of haystack) {
    if (ch === needle[pos]) pos += 1
    if (pos >= needle.length) return true
  }
  return false
}

function conversationSearchText(conv) {
  const messages = Array.isArray(conv?.messages)
    ? conv.messages.map(m => m?.content || '').join(' ')
    : ''
  return [
    conv?.skillName,
    conv?.preview,
    conv?.sessionId,
    messages,
  ].filter(Boolean).join(' ')
}

export function filterConversations(conversations, query) {
  const q = normalizeSearch(query)
  if (!q) return conversations || []
  return (conversations || []).filter(conv => {
    const text = normalizeSearch(conversationSearchText(conv))
    return text.includes(q) || isSubsequence(q, text)
  })
}
