'use strict';

function hasText(value) {
  return typeof value === 'string' && value.trim().length > 0;
}

function maxUserMsgCount(...values) {
  return Math.max(0, ...values.map(v => Number(v) || 0));
}

function agentSessionUserMsgCount(agent) {
  if (!agent) return 0;
  return maxUserMsgCount(agent.userMsgCount, agent.user_msg_count, agent.message_count);
}

function agentSessionHasConversationSignal(agent) {
  if (!agent) return false;
  return !!(
    agentSessionUserMsgCount(agent) > 0 ||
    hasText(agent.firstMessage) ||
    hasText(agent.first_message) ||
    hasText(agent.lastUserContent) ||
    hasText(agent.last_user_content) ||
    hasText(agent.firstAssistantText) ||
    hasText(agent.first_assistant_text) ||
    hasText(agent.renameName) ||
    hasText(agent.rename_name) ||
    hasText(agent.displayTitle) ||
    hasText(agent.aiTitle) ||
    hasText(agent.title)
  );
}

function collectAgentSessions(session, dbRow) {
  const agents = [];
  if (Array.isArray(session?.agentSessions)) agents.push(...session.agentSessions);
  if (Array.isArray(dbRow?.agent_sessions)) agents.push(...dbRow.agent_sessions);
  return agents;
}

function recentSessionHasConversationSignal(session, dbRow) {
  const agents = collectAgentSessions(session, dbRow);
  return !!(
    maxUserMsgCount(
      session?.userMsgCount,
      session?.user_msg_count,
      dbRow?.user_msg_count,
      ...agents.map(agentSessionUserMsgCount)
    ) > 0 ||
    hasText(session?.firstMessage) ||
    hasText(session?.first_message) ||
    hasText(session?.lastUserContent) ||
    hasText(session?.last_user_content) ||
    hasText(session?.firstAssistantText) ||
    hasText(session?.first_assistant_text) ||
    hasText(session?.renameName) ||
    hasText(session?.rename_name) ||
    hasText(session?.displayTitle) ||
    hasText(session?.aiTitle) ||
    hasText(session?.title) ||
    hasText(dbRow?.first_message) ||
    hasText(dbRow?.last_user_content) ||
    hasText(dbRow?.first_assistant_text) ||
    hasText(dbRow?.rename_name) ||
    hasText(dbRow?.title) ||
    agents.some(agentSessionHasConversationSignal)
  );
}

function applyRecentSessionEmptyState(session, dbRow) {
  if (!session) return session;
  const agents = collectAgentSessions(session, dbRow);
  session.userMsgCount = maxUserMsgCount(
    session.userMsgCount,
    session.user_msg_count,
    dbRow?.user_msg_count,
    ...agents.map(agentSessionUserMsgCount)
  );
  session.isEmpty = !recentSessionHasConversationSignal(session, dbRow);
  return session;
}

module.exports = {
  agentSessionHasConversationSignal,
  applyRecentSessionEmptyState,
  hasText,
  maxUserMsgCount,
  recentSessionHasConversationSignal,
};
