import { appConfig } from '../config';
import type { Session } from '../types';

export const DEFAULT_CHAT_TITLE = 'New Chat';

export function shouldShowNewChatTitle(session: Session): boolean {
  if (session.recipe) return false;
  return !session.user_set_name && session.message_count === 0;
}

export function sortAndTrim(sessions: Session[]): Session[] {
  return [...sessions]
    .sort((a, b) => {
      const aTime = new Date(a.updated_at ?? a.created_at ?? 0).getTime();
      const bTime = new Date(b.updated_at ?? b.created_at ?? 0).getTime();
      return bTime - aTime;
    })
    .slice(0, appConfig.sessionMaxCount);
}

export function prependUnique(prev: Session[], session: Session): Session[] {
  if (prev.some((s) => s.id === session.id)) return sortAndTrim(prev);
  return sortAndTrim([session, ...prev.filter((s) => s.id !== session.id)]);
}

export function touchSession(sessions: Session[], sessionId: string, messageDelta = 0): Session[] {
  const now = new Date().toISOString();
  return sortAndTrim(
    sessions.map((s) =>
      s.id === sessionId
        ? {
            ...s,
            updated_at: now,
            message_count: Math.max(0, s.message_count + messageDelta),
          }
        : s,
    ),
  );
}

export function getSessionDisplayName(session: Session): string {
  if (session.user_set_name) return session.name;
  if (session.recipe?.title) return session.recipe.title;
  if (shouldShowNewChatTitle(session)) return DEFAULT_CHAT_TITLE;
  return session.name;
}

function sameLocalDay(a: Date, b: Date): boolean {
  return (
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate()
  );
}

export function getSessionDateKey(session: Session): string {
  const iso = session.updated_at ?? session.created_at;
  if (!iso) return '';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';
  return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
}

export function formatSessionDateLabel(session: Session): string {
  const iso = session.updated_at ?? session.created_at;
  if (!iso) return '';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';

  const now = new Date();
  if (sameLocalDay(date, now)) return '今天';

  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  if (sameLocalDay(date, yesterday)) return '昨天';

  if (date.getFullYear() === now.getFullYear()) {
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  }

  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
}

export type SessionDateGroup = {
  dateKey: string;
  label: string;
  sessions: Session[];
};

export function groupSessionsByDate(sessions: Session[]): SessionDateGroup[] {
  const groups: SessionDateGroup[] = [];
  for (const session of sessions) {
    const dateKey = getSessionDateKey(session);
    const label = formatSessionDateLabel(session) || '未知日期';
    const last = groups[groups.length - 1];
    if (last && last.dateKey === dateKey) {
      last.sessions.push(session);
    } else {
      groups.push({ dateKey, label, sessions: [session] });
    }
  }
  return groups;
}

export function getSessionListLabel(session: Session): string {
  const displayName = getSessionDisplayName(session);
  if (displayName !== DEFAULT_CHAT_TITLE && displayName !== '新对话') {
    return displayName;
  }
  if (session.message_count > 0) {
    return `对话 · ${session.message_count} 条消息`;
  }
  return `会话 ${session.id.slice(0, 8)}`;
}
