// main.go
package main

import (
	"fmt"
	"log"

	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/api"
	"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/logger"
)

func main() {
	// 加载配置
	config.LoadConfig()
	if config.GlobalConfig == nil {
		log.Fatal("Failed to load configuration")
	}

	// 初始化日志系统
	loggerConfig := logger.LogConfig{
		Level:      config.GlobalConfig.Log.Level,
		Format:     config.GlobalConfig.Log.Format,
		Output:     config.GlobalConfig.Log.Output,
		FilePath:   config.GlobalConfig.Log.FilePath,
		MaxSize:    config.GlobalConfig.Log.MaxSize,
		MaxBackups: config.GlobalConfig.Log.MaxBackups,
		MaxAge:     config.GlobalConfig.Log.MaxAge,
		Compress:   config.GlobalConfig.Log.Compress,
	}
	logger.InitLogger(loggerConfig)

	// 初始化数据库
	database.InitDatabase()
	defer database.CloseDatabase()

	// 检查是否为生产环境
	isProduction := config.GlobalConfig.App.Environment == "production"

	// 生产环境下跳过数据库迁移和初始化操作
	if !isProduction {
		// 执行合并后的SQL以创建视图/触发器/扩展表（若尚未存在）
		if err := database.ApplyMergedSchemaIfNeeded(database.GetDB()); err != nil {
			log.Printf("Warning: Failed to apply merged schema: %v", err)
		}

		// 运行数据库迁移
		if err := database.AutoMigrate(database.GetDB()); err != nil {
			log.Fatalf("Failed to migrate database: %v", err)
		}

		// 创建索引
		if err := database.CreateIndexes(database.GetDB()); err != nil {
			log.Printf("Warning: Failed to create indexes: %v", err)
		}

		// 初始化种子数据
		if err := database.SeedData(database.GetDB()); err != nil {
			log.Printf("Warning: Failed to seed data: %v", err)
		}
	} else {
		log.Println("Production environment detected, skipping database migration and initialization")
	}

	// 记录启动信息
	logger.WithFields(map[string]interface{}{
		"app_name":    config.GlobalConfig.App.Name,
		"app_version": config.GlobalConfig.App.Version,
		"environment": config.GlobalConfig.App.Environment,
		"port":        config.GlobalConfig.Server.Port,
	}).Info("Starting AI English Learning Server")

	// 从 api 包获取配置好的路由引擎
	router := api.SetupRouter()

	// 启动服务
	port := fmt.Sprintf(":%s", config.GlobalConfig.Server.Port)
	logger.Infof("Server is running on port %s", config.GlobalConfig.Server.Port)
	if err := router.Run(port); err != nil {
		logger.Fatalf("Failed to start server: %v", err)
	}
}
