// src/views/chat/api/chat.api.ts
import { agentApplication, aiChat, aiModel, knowledge } from '@repo/api-service'
import type { ChatTargetConfig, ChatTargetType } from '../types'

export interface ChatRequestParams {
	sessionId: string
	query: string
	// 根据具体使用的聊天类型，可能需要其他参数，这里以 AgentChat 为例提供默认值
	knowledgeBaseIds?: string[]
	knowledgeIds?: string[]
	agentId?: string
	summaryModelId?: string
	disableTitle?: boolean
	enableMemory?: boolean
	images?: string[]
	agentEnabled?: boolean
	webSearchEnabled?: boolean
}

export interface ChatOptionItem {
	label: string
	value: string
	description?: string
	type?: string
	raw?: any
}

export function getChatUrl(type: ChatTargetType) {
	if (type === 'knowledge') return '/api/ai/chat/knowledge-chat'
	if (type === 'model') return '/api/ai/chat/model-chat'
	return '/api/ai/chat/agent-chat'
}

export function buildChatRequestBody(
	type: ChatTargetType,
	config: ChatTargetConfig,
	sessionId: string,
	query: string
) {
	const base = {
		session_id: sessionId,
		query,
		summary_model_id: config.summaryModelId || '',
		disable_title: config.disableTitle,
		enable_memory: config.enableMemory,
		channel: 'web'
	}

	if (type === 'knowledge') {
		return {
			...base,
			knowledge_base_ids: config.knowledgeBaseIds,
			knowledge_ids: config.knowledgeIds
		}
	}

	if (type === 'model') {
		return base
	}

	return {
		...base,
		knowledge_base_ids: config.knowledgeBaseIds,
		knowledge_ids: config.knowledgeIds,
		agent_id: config.agentId,
		images: config.images,
		agent_enabled: config.agentEnabled,
		web_search_enabled: config.webSearchEnabled
	}
}

/**
 * 发送聊天消息
 */
export async function sendChatMessage(params: ChatRequestParams) {
	// 这里默认使用 AgentChat，可以根据业务逻辑切换为 postChatKnowledgeChat 或 postChatModelChat
	return aiChat.postChatAgentChat({
		session_id: params.sessionId,
		query: params.query,
		knowledge_base_ids: params.knowledgeBaseIds || [],
		knowledge_ids: params.knowledgeIds || [],
		agent_id: params.agentId || '', // 需根据实际业务配置默认 agent_id
		summary_model_id: params.summaryModelId || '', // 需根据实际业务配置默认 model_id
		disable_title: params.disableTitle ?? false,
		enable_memory: params.enableMemory ?? true,
		images: params.images || [],
		agent_enabled: params.agentEnabled ?? true,
		web_search_enabled: params.webSearchEnabled ?? false
	})
}

export async function createSession(name: string) {
	return aiChat.postSessionCreate({ name })
}

export async function deleteSession(id: string) {
	return aiChat.postSessionOpenApiDelete({ id })
}

export async function updateSessionName(id: string, name: string) {
	return aiChat.postSessionUpdate({ id, name })
}

export async function getSessionList(pageIndex: number, pageSize: number) {
	return aiChat.postSessionPageList({ pageIndex, pageSize })
}

export async function getSessionMessages(
	sessionId: string,
	pageIndex: number = 1,
	pageSize: number = 100
) {
	return aiChat.postSessionSessionMessages({ sessionId, pageIndex, pageSize })
}

export async function getAgentOptions(keyword = ''): Promise<ChatOptionItem[]> {
	const res = await agentApplication.postAiAgentPageList({
		keyword,
		mode: '',
		type: '',
		pageIndex: 1,
		pageSize: 100
	})

	return (res.result?.model || []).map((item) => ({
		label: item.name || item.id || '',
		value: item.id || '',
		description: item.description,
		type: item.mode,
		raw: item
	}))
}

export async function getAgentInfo(id: string) {
	return agentApplication.postAiAgentInfo({ id })
}

export async function getKnowledgeBaseOptions(keyword = ''): Promise<ChatOptionItem[]> {
	const res = await knowledge.postKnowledgeBasePageList({
		keyword,
		type: '',
		pageIndex: 1,
		pageSize: 100
	})

	return (res.result?.model || []).map((item) => ({
		label: item.name || item.id || '',
		value: item.id || '',
		description: item.description,
		type: item.type,
		raw: item
	}))
}

export async function getModelOptions(keyword = ''): Promise<ChatOptionItem[]> {
	const res = await aiModel.postModelPageList({
		keyword,
		type: '',
		source: '',
		pageIndex: 1,
		pageSize: 100
	})

	return (res.result?.model || []).map((item) => ({
		label: item.title ? `${item.title} (${item.name})` : item.name || item.id || '',
		value: item.id || '',
		description: item.description,
		type: item.type,
		raw: item
	}))
}
