import request from '/@/utils/request';

export interface ModelModuleListParams {
	pageNum?: number;
	pageSize?: number;
	modelName?: string;
	modelType?: number | string;
	enabled?: number;
}

export interface ModelFormItem {
	field: string;
	label: string;
	required: boolean;
	type: 'input' | 'number' | 'textarea' | 'switch' | string;
}

export interface ModelFormEntry {
	key: string;
	value: string;
}

// 提示词管理接口类型
export interface PromptItem {
	id: number | string;
	tenantId?: number;
	creator?: string;
	createdAt?: string;
	updater?: string;
	updatedAt?: string;
	deletedAt?: string | null;
	nodeType: string;
	prompt: string;
	sourceType: number; // 0-自定义 1-公共
}

export interface PromptListResponse {
	list: PromptItem[];
	total: number;
}

export interface PromptListParams {
	pageNum?: number;
	pageSize?: number;
	keyword?: string;
}

export interface CreatePromptParams {
	nodeType: string;
	prompt: string;
	sourceType: number;
}

export interface UpdatePromptParams extends CreatePromptParams {
	id: number | string;
}

/** 模型类型（listType 接口项，字段名以后端为准，前端做兼容解析） */
export interface ModelTypeListItem {
	id?: number | string;
	typeId?: number | string;
	modelType?: number | string;
	name?: string;
	typeName?: string;
	label?: string;
}

/** listType 标准返回：data.type 为 Record<id, 名称>，如 { "1": "推理模型", "2": "图片模型" } */
export function normalizeModelTypeOptions(res: { data?: unknown }): Array<{ id: number | string; label: string }> {
	const data = res?.data as { type?: Record<string, string> } | undefined;
	const typeMap = data?.type;
	if (typeMap && typeof typeMap === 'object' && !Array.isArray(typeMap)) {
		return Object.entries(typeMap)
			.map(([key, label]) => {
				const n = Number(key);
				const id = Number.isNaN(n) ? key : n;
				return { id, label: String(label ?? '') };
			})
			.sort((a, b) => {
				const na = Number(a.id);
				const nb = Number(b.id);
				if (!Number.isNaN(na) && !Number.isNaN(nb)) {
					return na - nb;
				}
				return String(a.id).localeCompare(String(b.id));
			});
	}

	/** 兼容旧结构：data 为数组或 data.list */
	const raw = res?.data;
	const arr: ModelTypeListItem[] = Array.isArray(raw) ? raw : ((raw as { list?: ModelTypeListItem[] })?.list ?? []);
	return arr
		.map((item) => {
			const id = item.id ?? item.typeId ?? item.modelType;
			const label = item.name ?? item.typeName ?? item.label ?? (id != null && id !== '' ? String(id) : '');
			return { id: id as number | string, label: label || String(id) };
		})
		.filter((x) => x.id !== undefined && x.id !== null && x.id !== '');
}

export interface ModelModuleItem {
	id: number | string;
	tenantId?: number;
	creator?: string;
	createdAt?: string;
	updater?: string;
	updatedAt?: string;
	deletedAt?: string | null;
	isDeleted?: boolean;
	modelName: string;
	/** 模型类型 ID，与 listType 返回项对应 */
	modelType?: number | string;
	baseUrl: string;
	route?: string;
	httpMethod: string;
	apiKey?: string;
	isPrivate?: number;
	isChatModel?: number;
	/** 会话开关状态（列表接口返回，0 关 1 开；会话开关接口就绪后生效） */
	chatSessionEnabled?: number;
	enabled: number;
	/** 是否异步 0-同步 1-异步，依赖requestMapping */
	isAsync?: number;
	maxConcurrency: number;
	queueLimit: number;
	timeoutMs?: number;
	timeoutSeconds?: number;
	expectedSeconds?: number;
	retryTimes: number;
	retryQueueMaxSeconds: number;
	autoCleanSeconds: number;
	remark?: string;
	headMsg?: string | Record<string, string>;
	form?: ModelFormEntry[] | Record<string, { value: string }>;
	requestMapping?: Record<string, unknown>;
	responseMapping?: Record<string, unknown>;
}

export interface ModelModuleListResponse {
	code: number;
	message: string;
	data: {
		list: ModelModuleItem[];
		total: number;
	};
}

export interface CreateModelParams {
	modelName: string;
	/** 与 listType 返回的类型 id 一致，可能为数字或字符串 */
	modelType: number | string;
	operatorName?: string;
	baseUrl: string;
	httpMethod?: string;
	headMsg?: Record<string, string>;
	isPrivate: number;
	enabled: number;
	isChatModel: number;
	/** 是否异步 0-同步 1-异步，依赖requestMapping，默认0 */
	isAsync: number;
	apiKey?: string;
	form: ModelFormEntry[];
	requestMapping?: Record<string, unknown>;
	responseMapping?: Record<string, unknown>;
	responseBody?: Record<string, unknown>;
	extendMapping?: Record<string, unknown>;
	responseTokenField?: string;
	tokenConfig?: Record<string, unknown>;
	queryConfig?: Record<string, unknown>;
	maxConcurrency?: number;
	queueLimit?: number;
	timeoutSeconds: number;
	expectedSeconds: number;
	retryTimes?: number;
	retryQueueMaxSeconds: number;
	autoCleanSeconds: number;
	remark?: string;
}

export interface ModelConfigTypeItem {
	id: number | string;
	name: string;
	form: ModelFormItem[];
}

export interface ModelConfigGroup {
	typeId: number;
	type: string;
	items: ModelConfigTypeItem[];
}

export interface ModelConfigResponse {
	code: number;
	message: string;
	data: ModelConfigGroup[];
}

/**
 * 获取模型列表
 */
export function getModelModuleList(params?: ModelModuleListParams) {
	return request({
		url: '/model-gateway/model/listModel',
		method: 'get',
		params,
	});
}

/**
 * 获取模型类型列表（用于下拉与列表回显）
 */
export function getModelTypeList() {
	return request({
		url: '/model-gateway/model/listType',
		method: 'get',
	});
}

/**
 * 新增模型配置
 */
export function addModelModule(data: CreateModelParams) {
	return request({
		url: '/model-gateway/model/createModel',
		method: 'post',
		data,
	});
}

/**
 * 修改模型配置
 */
export function updateModelModule(data: Partial<CreateModelParams> & { id: number | string }) {
	return request({
		url: '/model-gateway/model/updateModel',
		method: 'put',
		data,
	});
}

/**
 * 删除模型配置
 */
export function deleteModelModule(id: number | string) {
	return request({
		url: '/model-gateway/model/deleteModel',
		method: 'delete',
		data: { id },
	});
}

/**
 * 获取单条模型配置详情（编辑用，需传 id）
 */
export function getModelModuleDetail(id: number | string) {
	return request({
		url: '/model-gateway/model/getModel',
		method: 'get',
		params: { id },
	});
}

/**
 * 更新模型会话开关状态
 */
export function updateChatModel(data: { id: number | string; isChatModel: 0 | 1 }) {
	return request({
		url: '/model-gateway/model/updateChatModel',
		method: 'post',
		data,
	});
}

/**
 * 获取当前会话模型
 */
export function getIsChatModel() {
	return request({
		url: '/model-gateway/model/getIsChatModel',
		method: 'get',
	});
}

/**
 * 获取服务商列表
 */
export function getOperatorList() {
	return request({
		url: '/model-gateway/model/listOperator',
		method: 'get',
	});
}

/**
 * 获取当前用户提示词列表
 */
export function getMyPromptList(params: PromptListParams) {
	return request<PromptListResponse>({
		url: '/node/prompt/listMy',
		method: 'get',
		params,
	});
}

/**
 * 创建提示词
 */
export function createPrompt(data: CreatePromptParams) {
	return request({
		url: '/node/prompt/create',
		method: 'post',
		data,
	});
}

/**
 * 修改提示词
 */
export function updatePrompt(data: UpdatePromptParams) {
	return request({
		url: '/node/prompt/update',
		method: 'put',
		data,
	});
}

/**
 * 删除提示词
 */
export function deletePrompt(id: number | string) {
	return request({
		url: `/node/prompt/delete/${id}`,
		method: 'delete',
	});
}
