package config

import (
	"fmt"
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"

	"github.com/spf13/viper"
)

type Config struct {
	Port              string
	JWTSecret         string
	DatabaseURL       string
	PythonServiceURL  string
	// 文件上传配置
	UploadMode      string // "local" 或 "minio"
	UploadLocalPath string // 本地存储路径，如 "resource/files"
	ServerBaseURL   string // 服务器基础 URL，用于生成本地文件 URL
	// MinIO 配置
	MinIOEndpoint   string
	MinIOAccessKey  string
	MinIOSecretKey  string
	MinIOBucket     string
	MinIOUseSSL    bool
}

func Load() *Config {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./config")
	viper.AddConfigPath("../config")
	viper.AddConfigPath("../../config")

	// 默认值
	viper.SetDefault("port", "8080")
	viper.SetDefault("jwt_secret", "your-secret-key-change-in-production")
	viper.SetDefault("python_service_url", "http://localhost:8081")
	viper.SetDefault("database_url", "root:root@tcp(localhost:3306)/x_agents?charset=utf8mb4&parseTime=True&loc=Local")
	// 文件上传默认配置
	viper.SetDefault("upload_mode", "local")
	viper.SetDefault("upload_local_path", "resource/files")
	viper.SetDefault("server_base_url", "http://localhost:8080")
	viper.SetDefault("minio_endpoint", "localhost:9000")
	viper.SetDefault("minio_access_key", "")
	viper.SetDefault("minio_secret_key", "")
	viper.SetDefault("minio_bucket", "x-agents")
	viper.SetDefault("minio_use_ssl", false)

	if err := viper.ReadInConfig(); err != nil {
		log.Printf("Using default config: %v", err)
	}

	return &Config{
		Port:             viper.GetString("port"),
		JWTSecret:        viper.GetString("jwt_secret"),
		DatabaseURL:      viper.GetString("database_url"),
		PythonServiceURL: viper.GetString("python_service_url"),
		// 文件上传配置
		UploadMode:      viper.GetString("upload_mode"),
		UploadLocalPath: viper.GetString("upload_local_path"),
		ServerBaseURL:   viper.GetString("server_base_url"),
		// MinIO 配置
		MinIOEndpoint:  viper.GetString("minio_endpoint"),
		MinIOAccessKey: viper.GetString("minio_access_key"),
		MinIOSecretKey: viper.GetString("minio_secret_key"),
		MinIOBucket:    viper.GetString("minio_bucket"),
		MinIOUseSSL:    viper.GetBool("minio_use_ssl"),
	}
}

func InitDB(cfg *Config) (*gorm.DB, error) {
	dsn := cfg.DatabaseURL
	if dsn == "" {
		return nil, fmt.Errorf("database URL is empty")
	}

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		return nil, fmt.Errorf("failed to connect database: %w", err)
	}

	log.Println("Database connected successfully")
	return db, nil
}
