export type UploadFileType = 'document' | 'image' | 'audio' | 'video' | 'custom'

export interface WorkflowUploadFile {
	id: string
	name: string
	extensionName: string
	size: number
	path: string
	contentType: string
}

// 文件类型分组和后缀白名单集中维护，start 节点配置和上传组件共用这一份定义。
export const FILE_EXTENSION_GROUPS: Record<Exclude<UploadFileType, 'custom'>, string[]> = {
	document: [
		'.txt',
		'.md',
		'.mdx',
		'.markdown',
		'.pdf',
		'.html',
		'.xlsx',
		'.xls',
		'.doc',
		'.docx',
		'.csv',
		'.eml',
		'.msg',
		'.pptx',
		'.ppt',
		'.xml',
		'.epub'
	],
	image: ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg'],
	audio: ['.mp3', '.m4a', '.wav', '.amr', '.mpga'],
	video: ['.mp4', '.mov', '.mpeg', '.webm']
}

export const normalizeFileExtension = (value: string) => {
	const text = `${value || ''}`.trim().toLowerCase()
	if (!text) return ''

	return text.startsWith('.') ? text : `.${text}`
}

export const getFileExtension = (value?: string) => {
	const text = `${value || ''}`.trim()
	if (!text) return ''

	const sanitized = text.split('?')[0]?.split('#')[0] || ''
	const extension = sanitized.match(/(\.[^.\\/]+)$/)?.[1] || ''
	return extension.toLowerCase()
}

// “分类文件类型”与“自定义后缀”会在这里合并成最终白名单。
export const getAllowedExtensions = (
	fileTypes: UploadFileType[] = [],
	fileExtensions: string[] = []
) => {
	const normalizedTypes = Array.isArray(fileTypes) ? fileTypes : []
	const normalizedExtensions = (Array.isArray(fileExtensions) ? fileExtensions : [])
		.map(normalizeFileExtension)
		.filter(Boolean)

	const extensionSet = new Set<string>()
	normalizedTypes.forEach((type) => {
		if (type === 'custom') return
		FILE_EXTENSION_GROUPS[type]?.forEach((extension) => extensionSet.add(extension))
	})

	normalizedExtensions.forEach((extension) => extensionSet.add(extension))
	return Array.from(extensionSet)
}

export const formatFileSize = (size?: number) => {
	if (!size || Number.isNaN(size) || size < 0) {
		return ''
	}

	if (size < 1024) {
		return `${size} B`
	}

	const kb = size / 1024
	if (kb < 1024) {
		return `${kb.toFixed(kb >= 100 ? 0 : 2)} KB`
	}

	const mb = kb / 1024
	if (mb < 1024) {
		return `${mb.toFixed(mb >= 100 ? 0 : 2)} MB`
	}

	const gb = mb / 1024
	return `${gb.toFixed(gb >= 100 ? 0 : 2)} GB`
}

export const getFileVisualType = (file: Partial<WorkflowUploadFile>) => {
	const extension = normalizeFileExtension(
		file.extensionName || getFileExtension(file.name || file.path)
	)

	if (FILE_EXTENSION_GROUPS.image.includes(extension)) return 'image'
	if (FILE_EXTENSION_GROUPS.audio.includes(extension)) return 'audio'
	if (FILE_EXTENSION_GROUPS.video.includes(extension)) return 'video'
	if (FILE_EXTENSION_GROUPS.document.includes(extension)) return 'document'

	return 'custom'
}
