import { DataModel, type KeyValue } from "@imengyu/js-request-transform";
import { appendGetUrlParams, assertNotNull, RandomUtils } from "@imengyu/imengyu-utils";
import { useAuthStore } from "@/store/auth";
import { RestfulApi } from "../restful";
import { SSE } from "./ssemp";
import type OpenAI from "openai";
import { CommonPageResult } from "@/api/restful/types";
import { AgentChatFile } from "./AgentChatFile";

/**
 * Agent 占位模型（用于复用 RestfulApi 的通用请求能力）
 */
export class AgentChatDummy extends DataModel<AgentChatDummy> {
  constructor() {
    super(AgentChatDummy, "AI对话");
  }
}

/**
 * AI 聊天会话
 */
export class AgentChatHistory extends DataModel<AgentChatHistory> {
  constructor() {
    super(AgentChatHistory, "AI聊天会话");
    this._convertTable = {
      createdAt: { clientSide: "date" },
    };
  }

  id = 0;
  /**
   * 用户ID
   */
  userId = 0;
  /**
   * 描述
   */
  desc = "";
  /**
   * 摘要
   */
  summary = "";
  /**
   * 长时记忆
   */
  longMemory = "";
  /**
   * 短时记忆
   */
  shortMemory = "";

  createdAt = new Date();
}

/**
 * AI 聊天会话项
 */
export class AgentChatHistoryItem extends DataModel<AgentChatHistoryItem> {
  constructor() {
    super(AgentChatHistoryItem, "AI聊天记录项");
    this._convertTable = {
      files: { clientSide: "array", clientSideChildDataModel: AgentChatFile, serverSide: 'undefined' },
      date: { clientSide: "date" },
    };
    this._blackList.toServer.push('userId','files');
  }

  id = 0;
  userId = 0;
  /**
   * 会话ID
   */
  historyId = 0;
  /**
   * 回复ID，针对用户消息
   */
  replyItemId = 0;
  /**
   * 父级ID,针对非用户消息，链接至用户消息
   */
  parentId = 0;
  /**
   * 额外信息
   */
  extra = "";
  /**
   * 状态
   */
  state = '';
  /**
   * 思考内容
   */
  reasoningContent = '';
  /**
   * 思考时间
   */
  reasoningTime = 0;
  /**
   * 回复时间
   */
  replyTime = 0;
  /** 
   * 回复AI名称
   */
  name = "";
  /**
   * 附件列表
   */
  files?: AgentChatFile[];
  date = new Date();
  role: "user" | "assistant" | "system" | "tool" | "" = "user";
  content = "";
  type = '';
}

/**
 * AI 聊天记录分组
 */
export class AgentChatHistoryGroup extends DataModel<AgentChatHistoryGroup> {
  constructor() {
    super(AgentChatHistoryGroup, "AI聊天记录分组");
  }

  id = 0;
  userId = 0;
  name = "";
  customPropmt = "";
  icon = "";
}

/**
 * SSE 推送消息结构（后端 chat-stream 写入的 data JSON）
 */
export type AgentChatStreamMessage =
  | { content: string }
  | { finished: true }
  | { error: string };

export type AgentChatModel = {
  /**
   * 模型名称
   */
  name: string;
  /**
   * 模型值
   */
  value: string;
  /**
   * 模型最大Tokens数
   */
  max_tokens: number;
  /**
   * 模型是否支持思考
   * @default false
   */
  can_think?: boolean;
  /**
   * 模型是否支持视觉
   * @default false
   */
  can_vl?: boolean;
  /**
   * 模型是否支持搜索
   * @default false
   */
  can_search?: boolean; 
  /**
   * 模型是否支持解析文档
   * @default false
   */
  can_prase_document?: boolean;
  /**
   * 模型是否支持读取音频
   * @default false
   */
  can_read_audio?: boolean;
  /**
   * 模型是否支持读取视频
   * @default false
   */
  can_read_video?: boolean;
  /**
   * 文档传输类型，用于指定文档在系统提示词中还是消息内容中
   * @default "in_system_prompt"
   */
  docunment_transfer_type?: "in_system_prompt" | "in_message_content";
  /**
   * 文档传输关键字，用于指定文档在系统提示词中还是消息内容中
   * @default ""
   */
  docunment_transfer_key?: string;
};

export class AgentApi extends RestfulApi<AgentChatDummy> {
  constructor() {
    super("content/agent", AgentChatDummy);
  }

  /**
   * 获取模型列表
   * 后端接口：GET /content/agent/model-list
   */
  getModelList() {
    return this.commonRquest<Record<string, AgentChatModel[]>>(
      "GET",
      `/${this.subResKey}/model-list`,
      "获取模型列表",
    );
  }
  /**
   * 非流式对话
   * 后端接口：POST /content/agent/chat，body: { options }
   */
  chat(options: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming) {
    return this.commonRquest<OpenAI.Chat.Completions.ChatCompletion>(
      "POST",
      `/${this.subResKey}/chat`,
      "AI对话（非流式）",
      { options },
    );
  }

  /**
   * 流式对话（SSE）
   * 后端接口：POST /content/agent/chat-stream，body: { options }
   *
   * 注意：此接口返回 text/event-stream，不走项目内通用的 JSON 包装协议。
   */
  chatStream(options: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming): SSE {
    const authStore = useAuthStore();
    const devUid = this.getDeviceUid();

    const url = appendGetUrlParams(
      `${this.config.baseUrl}/content/agent/chat-stream`,
      "identifier",
      devUid,
    );

    return new SSE(url, {
      headers: { 
        'Content-Type': 'application/json' ,
        token: authStore.token,
      },
      method: 'POST',
      payload: JSON.stringify({ options }),
      withCredentials: false,
      timeout: 60000,
    });
  }

  /**
   * 获取聊天会话分页（仅当前用户）
   * 后端接口：GET /content/agent/chat-history?page=&size=&search=
   */
  getChatHistory(page = 1, size = 10, search = "", groupId?: number) {
    return this.get<{
      allCount?: number;
      allPage?: number;
      items?: KeyValue[] | null;
    }>(
      "/content/agent/chat-history",
      "获取聊天会话分页列表",
      { page, size, search, groupId },
    ).then((rs) => {
      assertNotNull(rs.data, "rs.data is null!");
      return rs.cloneWithOtherData(
        new CommonPageResult<AgentChatHistory>().fromData(rs.data, page, size, AgentChatHistory),
      );
    });
  }

  /**
   * 获取聊天会话项分页（仅当前用户）
   * 后端接口：GET /content/agent/chat-history-items?page=&size=&id=
   */
  getChatHistoryItems(page = 1, size = 10, id = 0) {
    return this.get<{
      allCount?: number;
      allPage?: number;
      items?: KeyValue[] | null;
    }>(
      "/content/agent/chat-history-items",
      "获取聊天会话项分页列表",
      { 
        page, size, id, 
        sort: {
          field: 'date',
          order: 'asc',
        }
      },
    ).then((rs) => {
      assertNotNull(rs.data, "rs.data is null!");
      return rs.cloneWithOtherData(
        new CommonPageResult<AgentChatHistoryItem>().fromData(rs.data, page, size, AgentChatHistoryItem),
      );
    });
  }

  /**
   * 获取聊天记录分组分页（仅当前用户）
   * 后端接口：GET /content/agent/chat-history-groups?page=&size=
   */
  getChatHistoryGroups(page = 1, size = 10) {
    return this.get<{
      allCount?: number;
      allPage?: number;
      items?: KeyValue[] | null;
    }>(
      "/content/agent/chat-history-groups",
      "获取聊天记录分组分页列表",
      { page, size },
    ).then((rs) => {
      assertNotNull(rs.data, "rs.data is null!");
      return rs.cloneWithOtherData(
        new CommonPageResult<AgentChatHistoryGroup>().fromData(rs.data, page, size, AgentChatHistoryGroup),
      );
    });
  }

  /**
   * 创建聊天记录分组
   * 后端接口：POST /content/agent/chat-history-groups，body: { name, customPropmt, icon }
   */
  createChatHistoryGroup(name: string, customPropmt = "", icon = "") {
    return this.post<number>(
      "/content/agent/chat-history-groups",
      "创建聊天记录分组",
      { name, customPropmt, icon },
    );
  }

  /**
   * 更新聊天记录分组
   * 后端接口：PUT /content/agent/chat-history-groups/:id，body: { name, customPropmt, icon }
   */
  updateChatHistoryGroup(id: number, name: string, customPropmt = "", icon = "") {
    return this.put<unknown>(
      `/content/agent/chat-history-groups/${id}`,
      "更新聊天记录分组",
      { name, customPropmt, icon },
    );
  }

  /**
   * 删除聊天记录分组
   * 后端接口：DELETE /content/agent/chat-history-groups/:id
   */
  deleteChatHistoryGroup(id: number) {
    return this.delete<unknown>(
      `/content/agent/chat-history-groups/${id}`,
      "删除聊天记录分组",
    );
  }

  /**
   * 创建我的聊天会话
   * 后端接口：POST /content/agent/chat-history，body: { desc }
   */
  createChatHistory(desc: string, groupId?: number) {
    return this.post<number>(
      "/content/agent/chat-history",
      "创建聊天会话",
      { desc, groupId },
    );
  }

  /**
   * 更新我的聊天会话
   * 后端接口：PUT /content/agent/chat-history/:id，body: { data }
   */
  updateChatHistory(id: number, data: AgentChatHistory) {
    return this.put<unknown>(
      `/content/agent/chat-history/${id}`,
      "更新聊天会话",
      { data: data.toServerSide() },
    );
  }
  /**
   * 更新聊天记录项
   * 后端接口：PUT /content/agent/chat-history-items/:id，body: { data }
   */
  updateChatHistoryItem(id: number, data: AgentChatHistoryItem) {
    return this.put<unknown>(
      `/content/agent/chat-history-items/${id}`,
      "更新聊天记录项",
      { data: data.toServerSide() },
    );
  }

  /**
   * 删除我的聊天会话
   * 后端接口：DELETE /content/agent/chat-history/:id
   * @param id 聊天会话ID
   * @returns 删除结果
   */
  deleteChatHistory(id: number) {
    return this.delete<unknown>(
      `/content/agent/chat-history/${id}`,
      "删除聊天会话",
    );
  }

  /**
   * 向我的聊天会话添加/更新聊天记录项
   * 后端接口：POST /content/agent/chat-history-items/:historyId，body: { datas }
   */
  addOrUpdateChatHistoryItems(historyId: number, datas: AgentChatHistoryItem[], parentId?: number) {
    return this.post<number[]>(
      `/content/agent/chat-history-items/${historyId}`,
      "添加聊天记录项",
      { 
        datas: datas.map((k) => k.toServerSide()),
        parentId,
      },
    );
  }

  /**
   * 删除我的聊天会话的聊天记录项
   * 后端接口：POST /content/agent/chat-history-items/:historyId/delete，body: { ids }
   */
  deleteChatHistoryItems(historyId: number, ids: number[]) {
    return this.post<unknown>(
      `/content/agent/chat-history-items/${historyId}/delete`,
      "删除聊天记录项",
      { ids },
    );
  }
}

export default new AgentApi();

