/**
 * Segment utilities
 */

import type { MessageSegment, TextSegmentData, AtSegmentData, FileSegmentData, FaceSegmentData, LinkSegmentData, PostRefSegmentData } from './message';
import type { UserDTO } from './user';

// ==================== Chunk Types ====================

export type ContentChunk =
  | { kind: 'inline'; parts: MessageSegment[] }
  | { kind: 'images'; parts: MessageSegment[] }
  | { kind: 'block'; segment: MessageSegment };

/**
 * 将 segments 分成三种 chunk：
 * - inline: text / at / face 等行内元素
 * - images: 连续的图片 segment 组合
 * - block:  vote / post_ref / video / file / link / voice 等块级元素
 *
 * 与聊天和帖子详情共用同一套分组逻辑。
 */
export function partitionSegments(segments: MessageSegment[]): ContentChunk[] {
  const out: ContentChunk[] = [];
  let inlineBuf: MessageSegment[] = [];
  const flushInline = () => {
    if (inlineBuf.length) {
      out.push({ kind: 'inline', parts: [...inlineBuf] });
      inlineBuf = [];
    }
  };

  for (const s of segments) {
    if (s.type === 'image') {
      flushInline();
      const last = out[out.length - 1];
      if (last?.kind === 'images') {
        last.parts.push(s);
      } else {
        out.push({ kind: 'images', parts: [s] });
      }
    } else if (
      s.type === 'vote' ||
      s.type === 'post_ref' ||
      s.type === 'video' ||
      s.type === 'file' ||
      s.type === 'link' ||
      s.type === 'voice'
    ) {
      flushInline();
      out.push({ kind: 'block', segment: s });
    } else if (s.type === 'text' || s.type === 'at' || s.type === 'face') {
      inlineBuf.push(s);
    } else {
      // 未知类型也当作 inline 处理，避免丢失内容
      inlineBuf.push(s);
    }
  }
  flushInline();
  return out;
}

/**
 * Extract plain text from message segments for display
 */
export function extractTextFromSegments(segments?: MessageSegment[], memberMap?: Map<string, { nickname: string; user_id: string }>): string {
  if (!segments || segments.length === 0) {
    return '';
  }

  let result = '';

  for (const segment of segments) {
    switch (segment.type) {
      case 'text':
        const textData = segment.data as TextSegmentData;
        result += textData.content ?? textData.text ?? '';
        break;
      case 'at':
        const atData = segment.data as AtSegmentData;
        if (atData.user_id === 'all') {
          result += '@所有人 ';
        } else {
          const member = memberMap?.get(atData.user_id);
          const displayName = member?.nickname || atData.nickname || atData.user_id;
          result += `@${displayName} `;
        }
        break;
      case 'image':
        result += '[图片]';
        break;
      case 'voice':
        result += '[语音]';
        break;
      case 'video':
        result += '[视频]';
        break;
      case 'file':
        const fileData = segment.data as FileSegmentData;
        result += `[文件: ${fileData.name || '未知'}]`;
        break;
      case 'face':
        const faceData = segment.data as FaceSegmentData;
        result += faceData.name ? `[${faceData.name}]` : '[表情]';
        break;
      case 'link':
        const linkData = segment.data as LinkSegmentData;
        result += linkData.title ? `[链接: ${linkData.title}]` : '[链接]';
        break;
      case 'reply':
        break;
      case 'post_ref':
        const refData = segment.data as PostRefSegmentData;
        result += refData.title ? `[帖子: ${refData.title}]` : '[帖子引用]';
        break;
    }
  }

  return result.trim();
}

/**
 * Async version that resolves missing @at nicknames
 */
export async function extractTextFromSegmentsAsync(
  segments?: MessageSegment[],
  getUserCache?: (userId: string) => Promise<UserDTO | null>,
  getUserById?: (userId: string) => Promise<UserDTO | null>
): Promise<string> {
  if (!segments || segments.length === 0) {
    return '';
  }

  const resolvedSegments = [...segments];
  for (let i = 0; i < resolvedSegments.length; i++) {
    const segment = resolvedSegments[i];
    if (segment.type === 'at') {
      const atData = segment.data as AtSegmentData;
      if (atData.user_id !== 'all' && !atData.nickname) {
        try {
          let nickname = atData.user_id;
          if (getUserCache) {
            const cachedUser = await getUserCache(atData.user_id);
            if (cachedUser?.nickname) {
              nickname = cachedUser.nickname;
            } else if (getUserById) {
              const user = await getUserById(atData.user_id);
              if (user?.nickname) nickname = user.nickname;
            }
          } else if (getUserById) {
            const user = await getUserById(atData.user_id);
            if (user?.nickname) nickname = user.nickname;
          }
          resolvedSegments[i] = { ...segment, data: { ...atData, nickname } };
        } catch (error) {
          console.warn('[extractTextFromSegmentsAsync] 获取用户信息失败:', error);
        }
      }
    }
  }

  return extractTextFromSegments(resolvedSegments);
}