// 测试工具函数 - 验证多语言AI资讯系统各组件功能
// 严格遵循 UTS Android 开发规范

import type { 
	InfoContent, 
	TranslationData,
	CategoryData,
	ChatMessageData,
	UserSettingsData,
	PageState
} from './types.uts'

import {
	getContentId,
	getContentTitle,
	getContentSummary,
	getContentContent,
	getContentAuthor,
	getContentPublishedAt,
	getContentQualityScore,
	getContentViewCount,
	getContentLikeCount,
	getContentShareCount,
	getContentOriginalLanguage,
	getContentSourceUrl,
	getContentTags,
	formatDateTime,
	formatRelativeTime,
	getQualityScoreText,
	getQualityScoreColor,
	CATEGORIES,
	LANGUAGES,
	SORT_OPTIONS,
	DEFAULT_PAGE_SIZE
} from './types.uts'

// 测试数据生成器
export const createMockContent = (): InfoContent => {
	const content: InfoContent = {}
	content.set('id', `content_${Date.now()}`)
	content.set('title', 'AI技术发展趋势分析')
	content.set('content', '人工智能技术正在快速发展...')
	content.set('summary', '本文分析了AI技术的最新发展趋势')
	content.set('author', 'AI研究院')
	content.set('published_at', new Date().toISOString())
	content.set('quality_score', 0.85)
	content.set('view_count', 1250)
	content.set('like_count', 89)
	content.set('share_count', 23)
	content.set('original_language', 'zh-CN')
	content.set('source_url', 'https://example.com/ai-trends')
	content.set('tags', ['人工智能', '机器学习', '深度学习'])
	return content
}

export const createMockTranslation = (): TranslationData => {
	const translation: TranslationData = {}
	translation.set('id', `trans_${Date.now()}`)
	translation.set('content_id', 'content_123')
	translation.set('language_id', 'en-US')
	translation.set('title', 'AI Technology Development Trends Analysis')
	translation.set('content', 'Artificial intelligence technology is rapidly developing...')
	translation.set('summary', 'This article analyzes the latest AI development trends')
	translation.set('human_verified', true)
	translation.set('quality_score', 0.82)
	translation.set('created_at', new Date().toISOString())
	return translation
}

export const createMockCategory = (): CategoryData => {
	const category: CategoryData = {}
	category.set('id', `cat_${Date.now()}`)
	category.set('name_key', 'technology')
	category.set('display_order', 1)
	category.set('is_active', true)
	category.set('icon', '')
	category.set('color', '#3b82f6')
	return category
}

export const createMockChatMessage = (type: string): ChatMessageData => {
	const message: ChatMessageData = {}
	message.set('id', `msg_${Date.now()}`)
	message.set('session_id', 'session_123')
	message.set('type', type) // 'user' | 'assistant'
	message.set('content', type === 'user' ? '请推荐一些AI相关的资讯' : '为您推荐以下AI相关资讯...')
	message.set('created_at', new Date().toISOString())
	message.set('metadata', {})
	return message
}

export const createMockUserSettings = (): UserSettingsData => {
	const settings: UserSettingsData = {}
	settings.set('user_id', 'user_123')
	settings.set('interface_language', 'zh-CN')
	settings.set('preferred_languages', ['zh-CN', 'en-US'])
	settings.set('preferred_categories', ['technology', 'science'])
	settings.set('auto_translate', true)
	settings.set('notification_enabled', true)
	settings.set('reading_mode', 'normal')
	settings.set('font_size', 'medium')
	settings.set('theme', 'light')
	return settings
}

// 验证函数
export const validateContentData = (content: InfoContent): boolean => {
	try {
		// 验证必需字段
		const id = getContentId(content)
		const title = getContentTitle(content)
		const contentText = getContentContent(content)
		const author = getContentAuthor(content)
		const publishedAt = getContentPublishedAt(content)
		
		if (id === '' || title === '' || contentText === '' || author === '' || publishedAt === '') {
			console.error('Content validation failed: missing required fields')
			return false
		}
		
		// 验证数值字段
		const qualityScore = getContentQualityScore(content)
		const viewCount = getContentViewCount(content)
		const likeCount = getContentLikeCount(content)
		const shareCount = getContentShareCount(content)
		
		if (qualityScore < 0 || qualityScore > 1) {
			console.error('Content validation failed: invalid quality_score')
			return false
		}
		
		if (viewCount < 0 || likeCount < 0 || shareCount < 0) {
			console.error('Content validation failed: invalid count values')
			return false
		}
		
		// 验证标签数组
		const tags = getContentTags(content)
		if (tags.length > 10) {
			console.error('Content validation failed: too many tags')
			return false
		}
		
		return true
	} catch (error) {
		console.error('Content validation error:', error)
		return false
	}
}

export const validateTranslationData = (translation: TranslationData): boolean => {
	try {
		const id = translation.get('id') as string
		const contentId = translation.get('content_id') as string
		const languageId = translation.get('language_id') as string
		const title = translation.get('title') as string
		const content = translation.get('content') as string
		
		if (id === '' || contentId === '' || languageId === '' || title === '' || content === '') {
			console.error('Translation validation failed: missing required fields')
			return false
		}
		
		return true
	} catch (error) {
		console.error('Translation validation error:', error)
		return false
	}
}

// 性能测试函数
export const performanceTest = () => {
	console.log('开始性能测试...')
	
	const startTime = Date.now()
	
	// 创建大量测试数据
	const contents: Array<InfoContent> = []
	for (let i: Int = 0; i < 1000; i++) {
		contents.push(createMockContent())
	}
	
	// 测试数据处理速度
	let validCount: Int = 0
	for (let i: Int = 0; i < contents.length; i++) {
		const content = contents[i]
		if (validateContentData(content)) {
			validCount++
		}
	}
	
	const endTime = Date.now()
	const duration = endTime - startTime
	
	console.log(`性能测试完成:`)
	console.log(`- 处理数据量: ${contents.length}`)
	console.log(`- 有效数据: ${validCount}`)
	console.log(`- 耗时: ${duration}ms`)
	console.log(`- 平均处理速度: ${contents.length / duration * 1000}条/秒`)
}

// 功能测试函数
export const functionalTest = () => {
	console.log('开始功能测试...')
	
	// 测试内容数据处理
	const mockContent = createMockContent()
	console.log('✓ 内容数据创建成功')
	
	const isValidContent = validateContentData(mockContent)
	console.log(`✓ 内容数据验证: ${isValidContent ? '通过' : '失败'}`)
	
	// 测试翻译数据处理
	const mockTranslation = createMockTranslation()
	console.log('✓ 翻译数据创建成功')
	
	const isValidTranslation = validateTranslationData(mockTranslation)
	console.log(`✓ 翻译数据验证: ${isValidTranslation ? '通过' : '失败'}`)
	
	// 测试分类数据处理
	const mockCategory = createMockCategory()
	console.log('✓ 分类数据创建成功')
	
	// 测试聊天消息处理
	const mockUserMessage = createMockChatMessage('user')
	const mockAssistantMessage = createMockChatMessage('assistant')
	console.log('✓ 聊天消息创建成功')
	
	// 测试用户设置处理
	const mockSettings = createMockUserSettings()
	console.log('✓ 用户设置创建成功')
	
	// 测试工具函数
	const testDateTime = new Date().toISOString()
	const formattedDateTime = formatDateTime(testDateTime)
	const relativeTime = formatRelativeTime(testDateTime)
	console.log(`✓ 时间格式化测试: ${formattedDateTime}, ${relativeTime}`)
	
	const qualityScore = 0.85
	const qualityText = getQualityScoreText(qualityScore)
	const qualityColor = getQualityScoreColor(qualityScore)
	console.log(`✓ 质量分数测试: ${qualityText}, ${qualityColor}`)
	
	console.log('功能测试完成！')
}

// 集成测试函数
export const runAllTests = () => {
	console.log('=== 多语言AI资讯系统测试开始 ===')
	
	try {
		functionalTest()
		performanceTest()
		console.log('=== 所有测试通过 ===')
	} catch (error) {
		console.error('=== 测试失败 ===', error)
	}
}
