import * as base from './base.js';
import { generatePartId } from '../id.js';
import type { Part, PartType, ToolPart, ToolStatus } from '../parts.js';
import { PartSchema } from '../parts.js';

// Re-export types
export type { Part, PartType, ToolPart, ToolStatus } from '../parts.js';

/**
 * 创建 Part
 */
export async function create<T extends Part>(
  messageId: string,
  type: T['type'],
  data: Omit<T, 'id' | 'createdAt' | 'type'>
): Promise<T> {
  const part = {
    id: generatePartId(),
    createdAt: Date.now(),
    type,
    ...data,
  } as T;

  await base.write(['part', messageId, part.id], part);
  return part;
}

/**
 * 读取 Part
 */
export async function get(messageId: string, partId: string): Promise<Part | null> {
  try {
    return await base.read(['part', messageId, partId], PartSchema);
  } catch (e) {
    if (e instanceof base.StorageNotFoundError) {
      return null;
    }
    throw e;
  }
}

/**
 * 保存 Part
 */
export async function save(messageId: string, part: Part): Promise<void> {
  await base.write(['part', messageId, part.id], part);
}

/**
 * 更新 Part
 */
export async function update<T extends Part>(
  messageId: string,
  partId: string,
  updates: Partial<Omit<T, 'id' | 'createdAt' | 'type'>>
): Promise<Part> {
  return base.update(['part', messageId, partId], (part: Part) => {
    Object.assign(part, updates);
  });
}

/**
 * 更新 ToolPart 状态
 */
export async function updateToolStatus(
  messageId: string,
  partId: string,
  status: ToolStatus,
  result?: unknown,
  error?: string
): Promise<ToolPart> {
  return base.update(['part', messageId, partId], (part: ToolPart) => {
    part.status = status;
    if (status === 'running') {
      part.startedAt = Date.now();
    }
    if (status === 'completed' || status === 'error') {
      part.completedAt = Date.now();
      if (result !== undefined) {
        part.result = result;
      }
      if (error !== undefined) {
        part.error = error;
      }
    }
  }) as Promise<ToolPart>;
}

/**
 * 删除 Part
 */
export async function remove(messageId: string, partId: string): Promise<void> {
  await base.remove(['part', messageId, partId]);
}

/**
 * 列出消息的所有 Parts
 */
export async function listByMessage(messageId: string): Promise<Part[]> {
  const keys = await base.list(['part', messageId]);
  const parts: Part[] = [];

  for (const key of keys) {
    try {
      const part = await base.read<Part>(key, PartSchema);
      parts.push(part);
    } catch {
      // 跳过无法解析的文件
    }
  }

  // 按创建时间升序排列（Part ID 是升序的）
  return parts.sort((a, b) => a.createdAt - b.createdAt);
}

/**
 * 根据 Part IDs 获取 Parts（保持顺序）
 */
export async function getByIds(messageId: string, partIds: string[]): Promise<Part[]> {
  const parts: Part[] = [];

  for (const partId of partIds) {
    const part = await get(messageId, partId);
    if (part) {
      parts.push(part);
    }
  }

  return parts;
}

/**
 * 删除消息的所有 Parts
 */
export async function removeByMessage(messageId: string): Promise<void> {
  await base.removeDir(['part', messageId]);
}

/**
 * 创建文本 Part
 */
export async function createText(messageId: string, text: string): Promise<Part> {
  return create(messageId, 'text', { text });
}

/**
 * 创建工具调用 Part
 */
export async function createTool(
  messageId: string,
  toolCallId: string,
  toolName: string,
  args: Record<string, unknown>
): Promise<ToolPart> {
  return create<ToolPart>(messageId, 'tool', {
    toolCallId,
    toolName,
    args,
    status: 'pending',
  });
}

/**
 * 创建推理 Part
 */
export async function createReasoning(messageId: string, text: string): Promise<Part> {
  return create(messageId, 'reasoning', { text });
}
