// api/router.go
package api

import (
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/api/handlers"
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/config"
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/database"
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/handler"
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/middleware"
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/services"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

// SetupRouter 配置所有路由
func SetupRouter() *gin.Engine {
	// 根据环境设置Gin模式
	gin.SetMode(config.GlobalConfig.Server.Mode)
	
	// 创建路由引擎，不使用默认中间件
	router := gin.New()

	// 添加自定义中间件
	router.Use(middleware.RequestID())
    router.Use(middleware.RequestResponseLogger())
	router.Use(middleware.ErrorHandler())
	router.Use(middleware.CORS())
	router.Use(middleware.RateLimiter())

	// 静态文件服务 - 提供上传文件的访问
	router.Static("/uploads", "./uploads")

	// 初始化数据库连接
	db := database.GetDB()

	// 初始化验证器
	validate := validator.New()

	// 初始化服务
	userService := services.NewUserService(db)
	vocabularyService := services.NewVocabularyService(db)
	learningSessionService := services.NewLearningSessionService(db)
	listeningService := services.NewListeningService(db)
	readingService := services.NewReadingService(db)
	writingService := services.NewWritingService(db)
	speakingService := services.NewSpeakingService(db)
	testService := services.NewTestService(db)
	notificationService := services.NewNotificationService(db)
	wordBookService := services.NewWordBookService(db)
	studyPlanService := services.NewStudyPlanService(db)

	// 初始化处理器
	authHandler := handlers.NewAuthHandler(userService)
    userHandler := handlers.NewUserHandler(userService)
	vocabularyHandler := handler.NewVocabularyHandler(vocabularyService)
	learningSessionHandler := handler.NewLearningSessionHandler(learningSessionService)
	listeningHandler := handlers.NewListeningHandler(listeningService, validate)
	readingHandler := handlers.NewReadingHandler(readingService)
	writingHandler := handlers.NewWritingHandler(writingService)
	speakingHandler := handlers.NewSpeakingHandler(speakingService)
	testHandler := handlers.NewTestHandler(testService)
	notificationHandler := handler.NewNotificationHandler(notificationService)
	wordBookHandler := handler.NewWordBookHandler(wordBookService)
	studyPlanHandler := handler.NewStudyPlanHandler(studyPlanService)
	aiHandler := handler.NewAIHandler()
	uploadHandler := handler.NewUploadHandler()



	// 健康检查和系统信息路由
	router.GET("/health", handlers.HealthCheck)
	router.GET("/health/readiness", handlers.ReadinessCheck)
	router.GET("/health/liveness", handlers.LivenessCheck)
	router.GET("/version", handlers.GetVersion)

	// 为 /hello 路径注册 HelloHandler
	router.GET("/hello", handlers.HelloHandler)

	// 认证相关路由（无需认证）
	auth := router.Group("/api/v1/auth")
	{
		auth.POST("/register", authHandler.Register)
		auth.POST("/login", authHandler.Login)
		auth.POST("/refresh", authHandler.RefreshToken)
	}

	// 用户相关路由（需要认证）
	user := router.Group("/api/v1/user")
	user.Use(middleware.AuthMiddleware())
	{
		user.GET("/profile", userHandler.GetUserProfile)
		user.PUT("/profile", userHandler.UpdateUserProfile)
		user.GET("/stats", userHandler.GetUserStats)
		user.GET("/learning-progress", userHandler.GetUserLearningProgress)
		user.POST("/change-password", authHandler.ChangePassword)
	}

	// 词汇相关路由
	vocabulary := router.Group("/api/v1/vocabulary")
	vocabulary.Use(middleware.AuthMiddleware())
	{
		// 词汇分类
		vocabulary.GET("/categories", vocabularyHandler.GetCategories)
		vocabulary.POST("/categories", vocabularyHandler.CreateCategory)
		vocabulary.PUT("/categories/:id", vocabularyHandler.UpdateCategory)
		vocabulary.DELETE("/categories/:id", vocabularyHandler.DeleteCategory)

		// 词汇管理
		vocabulary.GET("/categories/:id/vocabularies", vocabularyHandler.GetVocabulariesByCategory)
		vocabulary.GET("/:id", vocabularyHandler.GetVocabularyByID)
		vocabulary.POST("/", vocabularyHandler.CreateVocabulary)
		vocabulary.GET("/search", vocabularyHandler.SearchVocabularies)

		// 用户单词学习进度
		vocabulary.GET("/words/:id/progress", vocabularyHandler.GetUserWordProgress)
		vocabulary.PUT("/words/:id/progress", vocabularyHandler.UpdateUserWordProgress)

		// 用户词汇进度
		vocabulary.GET("/progress/:id", vocabularyHandler.GetUserVocabularyProgress)
		vocabulary.PUT("/progress/:id", vocabularyHandler.UpdateUserVocabularyProgress)
		vocabulary.GET("/stats", vocabularyHandler.GetUserVocabularyStats)

		// 词汇测试
		vocabulary.POST("/tests", vocabularyHandler.CreateVocabularyTest)
		vocabulary.GET("/tests/:id", vocabularyHandler.GetVocabularyTest)
		vocabulary.PUT("/tests/:id/result", vocabularyHandler.UpdateVocabularyTestResult)

		// 每日学习统计
		vocabulary.GET("/daily", vocabularyHandler.GetDailyVocabularyStats)
		
		// 学习相关API
		vocabulary.GET("/study/today", vocabularyHandler.GetTodayStudyWords)
		vocabulary.GET("/study/statistics", vocabularyHandler.GetStudyStatistics)
		vocabulary.GET("/study/statistics/history", vocabularyHandler.GetStudyStatisticsHistory)
		
		// 词汇书相关API
		vocabulary.GET("/books/categories", vocabularyHandler.GetVocabularyBookCategories)
		vocabulary.GET("/books/system", vocabularyHandler.GetSystemVocabularyBooks)
		vocabulary.GET("/books/:id/words", vocabularyHandler.GetVocabularyBookWords)
		vocabulary.GET("/books/:id/progress", vocabularyHandler.GetVocabularyBookProgress)
		
		// 学习会话相关API
		vocabulary.POST("/books/:id/learn", learningSessionHandler.StartLearning)
		vocabulary.GET("/books/:id/tasks", learningSessionHandler.GetTodayTasks)
		vocabulary.GET("/books/:id/statistics", learningSessionHandler.GetLearningStatistics)
		vocabulary.POST("/words/:id/study", learningSessionHandler.SubmitWordStudy)
	}
	
	// 学习统计相关路由（全局统计，不限词汇书）
	learning := router.Group("/api/v1/learning")
	learning.Use(middleware.AuthMiddleware())
	{
		learning.GET("/today/statistics", learningSessionHandler.GetTodayOverallStatistics)
		learning.GET("/today/review-words", learningSessionHandler.GetTodayReviewWords)
	}

	// 听力训练相关路由
	listening := router.Group("/api/v1/listening")
	listening.Use(middleware.AuthMiddleware())
	{
		// 听力材料管理
		listening.GET("/materials", listeningHandler.GetListeningMaterials)
		listening.GET("/materials/:id", listeningHandler.GetListeningMaterial)
		listening.POST("/materials", listeningHandler.CreateListeningMaterial)
		listening.PUT("/materials/:id", listeningHandler.UpdateListeningMaterial)
		listening.DELETE("/materials/:id", listeningHandler.DeleteListeningMaterial)
		listening.GET("/materials/search", listeningHandler.SearchListeningMaterials)

		// 听力练习记录
		listening.POST("/records", listeningHandler.CreateListeningRecord)
		listening.PUT("/records/:id", listeningHandler.UpdateListeningRecord)
		listening.GET("/records", listeningHandler.GetUserListeningRecords)
		listening.GET("/records/:id", listeningHandler.GetListeningRecord)

		// 听力学习统计和进度
		listening.GET("/stats", listeningHandler.GetUserListeningStats)
		listening.GET("/progress/:material_id", listeningHandler.GetListeningProgress)
	}

	// 阅读理解相关路由
	reading := router.Group("/api/v1/reading")
	reading.Use(middleware.AuthMiddleware())
	{
		// 阅读材料管理
		reading.GET("/materials", readingHandler.GetReadingMaterials)
		reading.GET("/materials/:id", readingHandler.GetReadingMaterial)
		reading.POST("/materials", readingHandler.CreateReadingMaterial)
		reading.PUT("/materials/:id", readingHandler.UpdateReadingMaterial)
		reading.DELETE("/materials/:id", readingHandler.DeleteReadingMaterial)
		reading.GET("/materials/search", readingHandler.SearchReadingMaterials)

		// 阅读练习记录
		reading.POST("/records", readingHandler.CreateReadingRecord)
		reading.PUT("/records/:id", readingHandler.UpdateReadingRecord)
		reading.GET("/records", readingHandler.GetUserReadingRecords)
		reading.GET("/records/:id", readingHandler.GetReadingRecord)

		// 阅读学习统计和进度
		reading.GET("/stats", readingHandler.GetReadingStats)
		reading.GET("/progress/:material_id", readingHandler.GetReadingProgress)
		reading.GET("/recommendations", readingHandler.GetRecommendedMaterials)
	}

	// 写作练习相关路由
	writing := router.Group("/api/v1/writing")
	writing.Use(middleware.AuthMiddleware())
	{
		// 写作题目管理
		writing.GET("/prompts", writingHandler.GetWritingPrompts)
		writing.GET("/prompts/:id", writingHandler.GetWritingPrompt)
		writing.POST("/prompts", writingHandler.CreateWritingPrompt)
		writing.PUT("/prompts/:id", writingHandler.UpdateWritingPrompt)
		writing.DELETE("/prompts/:id", writingHandler.DeleteWritingPrompt)
		writing.GET("/prompts/search", writingHandler.SearchWritingPrompts)
		writing.GET("/prompts/recommendations", writingHandler.GetRecommendedPrompts)

		// 写作提交管理
		writing.POST("/submissions", writingHandler.CreateWritingSubmission)
		writing.GET("/submissions", writingHandler.GetUserWritingSubmissions)
		writing.GET("/submissions/:id", writingHandler.GetWritingSubmission)
		writing.PUT("/submissions/:id/submit", writingHandler.SubmitWriting)
		writing.PUT("/submissions/:id/grade", writingHandler.GradeWriting)

		// 写作学习统计和进度
		writing.GET("/stats", writingHandler.GetWritingStats)
		writing.GET("/progress/:prompt_id", writingHandler.GetWritingProgress)
	}

	// 口语练习相关路由
	speaking := router.Group("/api/v1/speaking")
	speaking.Use(middleware.AuthMiddleware())
	{
		// 口语场景管理
		speaking.GET("/scenarios", speakingHandler.GetSpeakingScenarios)
		speaking.GET("/scenarios/:id", speakingHandler.GetSpeakingScenario)
		speaking.POST("/scenarios", speakingHandler.CreateSpeakingScenario)
		speaking.PUT("/scenarios/:id", speakingHandler.UpdateSpeakingScenario)
		speaking.DELETE("/scenarios/:id", speakingHandler.DeleteSpeakingScenario)
		speaking.GET("/scenarios/search", speakingHandler.SearchSpeakingScenarios)
		speaking.GET("/scenarios/recommendations", speakingHandler.GetRecommendedScenarios)

		// 口语记录管理
		speaking.POST("/records", speakingHandler.CreateSpeakingRecord)
		speaking.GET("/records", speakingHandler.GetUserSpeakingRecords)
		speaking.GET("/records/:id", speakingHandler.GetSpeakingRecord)
		speaking.PUT("/records/:id/submit", speakingHandler.SubmitSpeaking)
		speaking.PUT("/records/:id/grade", speakingHandler.GradeSpeaking)

		// 口语学习统计和进度
		speaking.GET("/stats", speakingHandler.GetSpeakingStats)
		speaking.GET("/progress/:scenario_id", speakingHandler.GetSpeakingProgress)
	}

	// AI相关路由
	ai := router.Group("/api/v1/ai")
	ai.Use(middleware.AuthMiddleware())
	{
		// 写作批改
		ai.POST("/writing/correct", aiHandler.CorrectWriting)
		
		// 口语评估
		ai.POST("/speaking/evaluate", aiHandler.EvaluateSpeaking)
		
		// AI使用统计
		ai.GET("/stats", aiHandler.GetAIUsageStats)
	}

	// 文件上传相关路由
	upload := router.Group("/api/v1/upload")
	upload.Use(middleware.AuthMiddleware())
	{
		// 音频文件上传
		upload.POST("/audio", uploadHandler.UploadAudio)
		
		// 图片文件上传
		upload.POST("/image", uploadHandler.UploadImage)
		
		// 文件信息查询
		upload.GET("/file/:file_id", uploadHandler.GetFileInfo)
		
		// 文件删除
		upload.DELETE("/file/:file_id", uploadHandler.DeleteFile)
		
		// 上传统计
		upload.GET("/stats", uploadHandler.GetUploadStats)
	}

	// 综合测试相关路由
	test := router.Group("/api/v1/tests")
	test.Use(middleware.AuthMiddleware())
	{
		// 测试模板管理
		test.GET("/templates", testHandler.GetTestTemplates)
		test.GET("/templates/:id", testHandler.GetTestTemplateByID)

		// 测试会话管理
		test.POST("/sessions", testHandler.CreateTestSession)
		test.GET("/sessions", testHandler.GetUserTestHistory)
		test.GET("/sessions/:id", testHandler.GetTestSession)
		test.PUT("/sessions/:id/start", testHandler.StartTest)
		test.POST("/sessions/:id/answers", testHandler.SubmitAnswer)
		test.PUT("/sessions/:id/pause", testHandler.PauseTest)
		test.PUT("/sessions/:id/resume", testHandler.ResumeTest)
		test.PUT("/sessions/:id/complete", testHandler.CompleteTest)

		// 测试结果管理
		test.GET("/results/:id", testHandler.GetTestResultByID)
		test.DELETE("/results/:id", testHandler.DeleteTestResult)

		// 测试统计
		test.GET("/stats", testHandler.GetUserTestStats)
	}

	// 通知相关路由
	notification := router.Group("/api/v1/notifications")
	notification.Use(middleware.AuthMiddleware())
	{
		// 获取通知列表
		notification.GET("", notificationHandler.GetNotifications)
		// 获取未读通知数量
		notification.GET("/unread-count", notificationHandler.GetUnreadCount)
		// 标记通知为已读
		notification.PUT("/:id/read", notificationHandler.MarkAsRead)
		// 标记所有通知为已读
		notification.PUT("/read-all", notificationHandler.MarkAllAsRead)
		// 删除通知
		notification.DELETE("/:id", notificationHandler.DeleteNotification)
	}

	// 生词本相关路由
	wordBook := router.Group("/api/v1/word-book")
	wordBook.Use(middleware.AuthMiddleware())
	{
		// 切换收藏状态
		wordBook.POST("/toggle/:id", wordBookHandler.ToggleFavorite)
		// 获取生词本列表
		wordBook.GET("", wordBookHandler.GetFavoriteWords)
		// 获取指定词汇书的生词本
		wordBook.GET("/books/:id", wordBookHandler.GetFavoriteWordsByBook)
		// 获取生词本统计
		wordBook.GET("/stats", wordBookHandler.GetFavoriteStats)
		// 批量添加到生词本
		wordBook.POST("/batch", wordBookHandler.BatchAddToFavorite)
		// 从生词本移除
		wordBook.DELETE("/:id", wordBookHandler.RemoveFromFavorite)
	}

	// 学习计划相关路由
	studyPlan := router.Group("/api/v1/study-plans")
	studyPlan.Use(middleware.AuthMiddleware())
	{
		// 创建学习计划
		studyPlan.POST("", studyPlanHandler.CreateStudyPlan)
		// 获取学习计划列表
		studyPlan.GET("", studyPlanHandler.GetUserStudyPlans)
		// 获取今日计划
		studyPlan.GET("/today", studyPlanHandler.GetTodayStudyPlans)
		// 获取计划详情
		studyPlan.GET("/:id", studyPlanHandler.GetStudyPlanByID)
		// 更新计划
		studyPlan.PUT("/:id", studyPlanHandler.UpdateStudyPlan)
		// 删除计划
		studyPlan.DELETE("/:id", studyPlanHandler.DeleteStudyPlan)
		// 更新计划状态
		studyPlan.PATCH("/:id/status", studyPlanHandler.UpdatePlanStatus)
		// 记录学习进度
		studyPlan.POST("/:id/progress", studyPlanHandler.RecordStudyProgress)
		// 获取计划统计
		studyPlan.GET("/:id/statistics", studyPlanHandler.GetStudyPlanStatistics)
	}

	return router
}
