package database

import (
	"log"
	"time"

	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/models"
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/utils"
	"gorm.io/gorm"
)

// stringPtr 返回字符串指针
func stringPtr(s string) *string {
	return &s
}

// SeedData 初始化种子数据
func SeedData(db *gorm.DB) error {
	log.Println("开始初始化种子数据...")

	// 检查是否已有数据
	var userCount int64
	db.Model(&models.User{}).Count(&userCount)
	if userCount > 0 {
		log.Println("数据库已有数据，跳过种子数据初始化")
		return nil
	}

	// 创建词汇分类
	if err := createVocabularyCategories(db); err != nil {
		return err
	}

	// 创建示例词汇
	if err := createSampleVocabularies(db); err != nil {
		return err
	}

	// 创建测试用户
	if err := createTestUsers(db); err != nil {
		return err
	}

	// 创建听力材料
	if err := createListeningMaterials(db); err != nil {
		return err
	}

	// 创建阅读材料
	if err := createReadingMaterials(db); err != nil {
		return err
	}

	// 创建写作提示
	if err := createWritingPrompts(db); err != nil {
		return err
	}

	// 创建口语场景
	if err := createSpeakingScenarios(db); err != nil {
		return err
	}

	log.Println("种子数据初始化完成")
	return nil
}

// createVocabularyCategories 创建词汇分类
func createVocabularyCategories(db *gorm.DB) error {
	categories := []models.VocabularyCategory{
		{
			ID:          utils.GenerateUUID(),
			Name:        "日常生活",
			Description: stringPtr("日常生活中常用的词汇"),
			Level:       "beginner",
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
		{
			ID:          utils.GenerateUUID(),
			Name:        "商务英语",
			Description: stringPtr("商务场景中使用的专业词汇"),
			Level:       "intermediate",
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
		{
			ID:          utils.GenerateUUID(),
			Name:        "学术英语",
			Description: stringPtr("学术研究和论文写作中的词汇"),
			Level:       "advanced",
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
		{
			ID:          utils.GenerateUUID(),
			Name:        "旅游英语",
			Description: stringPtr("旅游出行相关的实用词汇"),
			Level:       "beginner",
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
		{
			ID:          utils.GenerateUUID(),
			Name:        "科技英语",
			Description: stringPtr("科技和互联网相关词汇"),
			Level:       "intermediate",
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
	}

	for _, category := range categories {
		if err := db.Create(&category).Error; err != nil {
			return err
		}
	}

	log.Println("词汇分类创建完成")
	return nil
}

// createSampleVocabularies 创建示例词汇
func createSampleVocabularies(db *gorm.DB) error {
	// 获取第一个分类ID
	var category models.VocabularyCategory
	if err := db.First(&category).Error; err != nil {
		return err
	}

	vocabularies := []struct {
		Word        string
		Phonetic    string
		Level       string
		Frequency   int
		Definitions []models.VocabularyDefinition
		Examples    []models.VocabularyExample
	}{
		{
			Word:      "hello",
			Phonetic:  "/həˈloʊ/",
			Level:     "beginner",
			Frequency: 100,
			Definitions: []models.VocabularyDefinition{
				{
					PartOfSpeech: "interjection",
					Definition:   "used as a greeting or to begin a phone conversation",
					Translation:  "你好",
					SortOrder:    0,
					CreatedAt:    time.Now(),
				},
			},
			Examples: []models.VocabularyExample{
				{
					Example:     "Hello, how are you?",
					Translation: "你好，你好吗？",
					SortOrder:   0,
					CreatedAt:   time.Now(),
				},
			},
		},
		{
			Word:      "world",
			Phonetic:  "/wɜːrld/",
			Level:     "beginner",
			Frequency: 95,
			Definitions: []models.VocabularyDefinition{
				{
					PartOfSpeech: "noun",
					Definition:   "the earth, together with all of its countries and peoples",
					Translation:  "世界",
					SortOrder:    0,
					CreatedAt:    time.Now(),
				},
			},
			Examples: []models.VocabularyExample{
				{
					Example:     "The world is a beautiful place.",
					Translation: "世界是一个美丽的地方。",
					SortOrder:   0,
					CreatedAt:   time.Now(),
				},
			},
		},
		{
			Word:      "learn",
			Phonetic:  "/lɜːrn/",
			Level:     "beginner",
			Frequency: 90,
			Definitions: []models.VocabularyDefinition{
				{
					PartOfSpeech: "verb",
					Definition:   "acquire knowledge of or skill in something",
					Translation:  "学习",
					SortOrder:    0,
					CreatedAt:    time.Now(),
				},
			},
			Examples: []models.VocabularyExample{
				{
					Example:     "I want to learn English.",
					Translation: "我想学习英语。",
					SortOrder:   0,
					CreatedAt:   time.Now(),
				},
			},
		},
		{
			Word:      "study",
			Phonetic:  "/ˈstʌdi/",
			Level:     "beginner",
			Frequency: 85,
			Definitions: []models.VocabularyDefinition{
				{
					PartOfSpeech: "verb",
					Definition:   "devote time and attention to acquiring knowledge",
					Translation:  "学习，研究",
					SortOrder:    0,
					CreatedAt:    time.Now(),
				},
			},
			Examples: []models.VocabularyExample{
				{
					Example:     "She studies hard every day.",
					Translation: "她每天都努力学习。",
					SortOrder:   0,
					CreatedAt:   time.Now(),
				},
			},
		},
		{
			Word:      "practice",
			Phonetic:  "/ˈpræktɪs/",
			Level:     "intermediate",
			Frequency: 80,
			Definitions: []models.VocabularyDefinition{
				{
					PartOfSpeech: "verb",
					Definition:   "perform an activity repeatedly to improve one's skill",
					Translation:  "练习",
					SortOrder:    0,
					CreatedAt:    time.Now(),
				},
			},
			Examples: []models.VocabularyExample{
				{
					Example:     "Practice makes perfect.",
					Translation: "熟能生巧。",
					SortOrder:   0,
					CreatedAt:   time.Now(),
				},
			},
		},
	}

	for _, vocabData := range vocabularies {
		// 检查词汇是否已存在
		var existingVocab models.Vocabulary
		if err := db.Where("word = ?", vocabData.Word).First(&existingVocab).Error; err == nil {
			// 词汇已存在，跳过
			log.Printf("词汇 '%s' 已存在，跳过创建", vocabData.Word)
			continue
		}

		// 创建词汇
		vocab := models.Vocabulary{
			Word:      vocabData.Word,
			Phonetic:  &vocabData.Phonetic,
			Level:     vocabData.Level,
			Frequency: vocabData.Frequency,
			IsActive:  true,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}

		if err := db.Create(&vocab).Error; err != nil {
			return err
		}

		// 关联分类
		if err := db.Model(&vocab).Association("Categories").Append(&category); err != nil {
			return err
		}

		// 创建定义
		for _, def := range vocabData.Definitions {
			def.VocabularyID = vocab.ID
			if err := db.Create(&def).Error; err != nil {
				return err
			}
		}

		// 创建例句
		for _, example := range vocabData.Examples {
			example.VocabularyID = vocab.ID
			if err := db.Create(&example).Error; err != nil {
				return err
			}
		}
	}

	log.Println("示例词汇创建完成")
	return nil
}

// createTestUsers 创建测试用户
func createTestUsers(db *gorm.DB) error {
	users := []models.User{
		{
			ID:            0, // 让数据库自动生成
			Username:      "testuser",
			Email:         "test@example.com",
			PasswordHash:  "$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", // password
			Nickname:      stringPtr("测试用户"),
			Avatar:        stringPtr("https://via.placeholder.com/150"),
			Gender:        stringPtr("other"),
			BirthDate:     nil,
			Location:      stringPtr("北京"),
			Bio:           stringPtr("这是一个测试用户"),
			EmailVerified: true,
			Status:        "active",
			CreatedAt:     time.Now(),
			UpdatedAt:     time.Now(),
		},
		{
			ID:            0, // 让数据库自动生成
			Username:      "demo",
			Email:         "demo@example.com",
			PasswordHash:  "$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", // password
			Nickname:      stringPtr("演示用户"),
			Avatar:        stringPtr("https://via.placeholder.com/150"),
			Gender:        stringPtr("other"),
			BirthDate:     nil,
			Location:      stringPtr("上海"),
			Bio:           stringPtr("这是一个演示用户"),
			EmailVerified: true,
			Status:        "active",
			CreatedAt:     time.Now(),
			UpdatedAt:     time.Now(),
		},
	}

	for _, user := range users {
		if err := db.Create(&user).Error; err != nil {
			return err
		}

		// 创建用户偏好设置
        preference := models.UserPreference{
            ID:                   0, // 让数据库自动生成
            UserID:               user.ID,
            DailyGoal:            30,
            WeeklyGoal:           210,
            ReminderEnabled:      true,
            ReminderTime:         stringPtr("09:00:00"),
            DifficultyLevel:      "intermediate",
            LearningMode:         "casual",
            PreferredTopics:      stringPtr("[\"vocabulary\", \"listening\"]"),
            NotificationSettings: stringPtr("{\"email\": true, \"push\": true}"),
            PrivacySettings:      stringPtr("{\"profile_public\": false}"),
            CreatedAt:            time.Now(),
            UpdatedAt:            time.Now(),
        }
		if err := db.Create(&preference).Error; err != nil {
			return err
		}
	}

	log.Println("测试用户创建完成")
	return nil
}

// createListeningMaterials 创建听力材料
func createListeningMaterials(db *gorm.DB) error {
	materials := []models.ListeningMaterial{
		{
			ID:          utils.GenerateUUID(),
			Title:       "Daily Conversation",
			Description: stringPtr("Basic daily conversation practice"),
			Level:       "beginner",
			Duration:    180, // 3 minutes
			AudioURL:    "https://example.com/audio/daily-conversation.mp3",
			Transcript:  stringPtr("A: Hello, how are you today? B: I'm fine, thank you. How about you?"),
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
		{
			ID:          utils.GenerateUUID(),
			Title:       "Business Meeting",
			Description: stringPtr("Business meeting discussion"),
			Level:       "intermediate",
			Duration:    300, // 5 minutes
			AudioURL:    "https://example.com/audio/business-meeting.mp3",
			Transcript:  stringPtr("Let's discuss the quarterly report and our future plans."),
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
	}

	for _, material := range materials {
		if err := db.Create(&material).Error; err != nil {
			return err
		}
	}

	log.Println("听力材料创建完成")
	return nil
}

// intPtr 返回整数指针
func intPtr(i int) *int {
	return &i
}

// createReadingMaterials 创建阅读材料
func createReadingMaterials(db *gorm.DB) error {
	materials := []models.ReadingMaterial{
		{
			ID:          utils.GenerateUUID(),
			Title:       "The Benefits of Reading",
			Content:     "Reading is one of the most beneficial activities for the human mind. It improves vocabulary, enhances critical thinking, and provides entertainment.",
			Level:       "beginner",
			WordCount:   25,
			
			Summary:     stringPtr("这是一篇关于阅读益处的文章"),
			Source:      stringPtr("Education Weekly"),
			Author:      stringPtr("Reading Expert"),
			Tags:        stringPtr("[\"reading\", \"education\"]"),
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
		{
			ID:          utils.GenerateUUID(),
			Title:       "Climate Change and Technology",
			Content:     "Climate change represents one of the most pressing challenges of our time. Technology plays a crucial role in both contributing to and solving environmental problems.",
			Level:       "intermediate",
			WordCount:   30,
			
			Summary:     stringPtr("这是一篇关于气候变化与科技的文章"),
			Source:      stringPtr("Science Today"),
			Author:      stringPtr("Climate Researcher"),
			Tags:        stringPtr("[\"climate\", \"technology\"]"),
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
	}

	for _, material := range materials {
		if err := db.Create(&material).Error; err != nil {
			return err
		}
	}

	log.Println("阅读材料创建完成")
	return nil
}

// createWritingPrompts 创建写作提示
func createWritingPrompts(db *gorm.DB) error {
	prompts := []models.WritingPrompt{
		{
			ID:           utils.GenerateUUID(),
			Title:        "My Daily Routine",
			Prompt:       "Describe your daily routine from morning to evening. Include what you do, when you do it, and why.",
			Level:        "beginner",
			MinWords:     intPtr(100),
            MaxWords:     intPtr(200),
            TimeLimit:    intPtr(1800), // 30 minutes
			Instructions: stringPtr("Write a clear and descriptive essay"),
			Tags:         stringPtr("[\"daily\", \"routine\"]"),
			SampleAnswer: stringPtr("Every morning, I wake up at 7 AM and start my day..."),
			Rubric:       stringPtr("{\"grammar\": 25, \"vocabulary\": 25, \"coherence\": 25, \"content\": 25}"),
			IsActive:     true,
			CreatedAt:    time.Now(),
			UpdatedAt:    time.Now(),
		},
		{
			ID:           utils.GenerateUUID(),
			Title:        "The Impact of Social Media",
			Prompt:       "Discuss the positive and negative impacts of social media on modern society. Provide specific examples and your personal opinion.",
			Level:        "intermediate",
			MinWords:     intPtr(250),
            MaxWords:     intPtr(400),
            TimeLimit:    intPtr(2700), // 45 minutes
			Instructions: stringPtr("Write a balanced argumentative essay"),
			Tags:         stringPtr("[\"social media\", \"society\"]"),
			SampleAnswer: stringPtr("Social media has transformed how we communicate..."),
			Rubric:       stringPtr("{\"grammar\": 30, \"vocabulary\": 20, \"coherence\": 25, \"content\": 25}"),
			IsActive:     true,
			CreatedAt:    time.Now(),
			UpdatedAt:    time.Now(),
		},
	}

	for _, prompt := range prompts {
		if err := db.Create(&prompt).Error; err != nil {
			return err
		}
	}

	log.Println("写作提示创建完成")
	return nil
}

// createSpeakingScenarios 创建口语场景
func createSpeakingScenarios(db *gorm.DB) error {
	scenarios := []models.SpeakingScenario{
		{
			ID:          utils.GenerateUUID(),
			Title:       "Restaurant Ordering",
			Description: "You are at a restaurant and want to order food. The waiter will take your order.",
			Level:       "beginner",
			Context:     stringPtr("You are at a restaurant with friends"),
			Tags:        stringPtr("[\"restaurant\", \"food\"]"),
			Dialogue:    stringPtr("[{\"speaker\": \"waiter\", \"text\": \"Good evening, welcome to our restaurant!\"}]"),
			KeyPhrases:  stringPtr("[\"I'd like to order\", \"Could I have\", \"The bill, please\"]"),
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
		{
			ID:          utils.GenerateUUID(),
			Title:       "Job Interview",
			Description: "You are in a job interview for a position you really want. Answer the interviewer's questions confidently.",
			Level:       "intermediate",
			Context:     stringPtr("You are applying for a job"),
			Tags:        stringPtr("[\"interview\", \"job\"]"),
			Dialogue:    stringPtr("[{\"speaker\": \"interviewer\", \"text\": \"Tell me about yourself\"}]"),
			KeyPhrases:  stringPtr("[\"I have experience in\", \"My strengths are\", \"I'm interested in\"]"),
			IsActive:    true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		},
	}

	for _, scenario := range scenarios {
		if err := db.Create(&scenario).Error; err != nil {
			return err
		}
	}

	log.Println("口语场景创建完成")
	return nil
}