package config

import (
	"fmt"
	"os"
	"strings"

	"gopkg.in/yaml.v3"
)

type Config struct {
	Server struct {
		Port int    `yaml:"port"`
		Key  string `yaml:"key"`
	} `yaml:"server"`
	Database struct {
		Path string `yaml:"path"`
	} `yaml:"database"`
	Telegram struct {
		Enabled bool   `yaml:"enabled"`
		Token   string `yaml:"token"`
	} `yaml:"telegram"`
	QQBot struct {
		Enabled bool   `yaml:"enabled"`
		AppID   string `yaml:"appid"`
		Secret  string `yaml:"secret"`
	} `yaml:"qqbot"`
	Feishu struct {
		Enabled           bool   `yaml:"enabled"`
		AppID             string `yaml:"app_id"`
		AppSecret         string `yaml:"app_secret"`
		VerificationToken string `yaml:"verification_token"`
		EncryptKey        string `yaml:"encrypt_key"`
	} `yaml:"feishu"`
	AI struct {
		Enabled        bool   `yaml:"enabled"`
		BaseURL        string `yaml:"base_url"`
		APIKey         string `yaml:"api_key"`
		Model          string `yaml:"model"`
		TimeoutSeconds int    `yaml:"timeout_seconds"`
	} `yaml:"ai"`
	Admin struct {
		Username string `yaml:"username"`
		Password string `yaml:"password"`
	} `yaml:"admin"`
}

func LoadConfig(path string) (*Config, error) {
	cfg := &Config{}
	file, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("打开配置文件失败: %w", err)
	}
	defer file.Close()

	d := yaml.NewDecoder(file)
	if err := d.Decode(&cfg); err != nil {
		return nil, fmt.Errorf("解析配置文件失败: %w", err)
	}

	if err := cfg.Validate(); err != nil {
		return nil, fmt.Errorf("配置验证失败: %w", err)
	}

	return cfg, nil
}

func IsWeakPassword(pw string) bool {
	p := strings.TrimSpace(pw)
	if p == "" {
		return true
	}
	weak := map[string]bool{
		"admin123":      true,
		"your_password": true,
		"CHANGE_ME":     true,
		"change_me":     true,
		"password":      true,
		"123456":        true,
		"12345678":      true,
		"qwerty":        true,
	}
	return weak[p]
}

func (c *Config) Validate() error {
	if c.Database.Path == "" {
		return fmt.Errorf("database.path 不能为空")
	}
	if c.Server.Port <= 0 || c.Server.Port > 65535 {
		return fmt.Errorf("server.port 必须在 1-65535 之间，当前值: %d", c.Server.Port)
	}
	if c.Server.Key == "" {
		return fmt.Errorf("server.key 不能为空（用于会话签名）")
	}
	if c.Admin.Username == "" || c.Admin.Password == "" {
		return fmt.Errorf("admin.username 和 admin.password 不能为空")
	}
	if c.Telegram.Enabled && c.Telegram.Token == "" {
		return fmt.Errorf("telegram 已启用但 token 为空")
	}
	if c.QQBot.Enabled {
		if c.QQBot.AppID == "" || c.QQBot.Secret == "" {
			return fmt.Errorf("qqbot 已启用但 appid 或 secret 为空")
		}
	}
	if c.Feishu.Enabled {
		if c.Feishu.AppID == "" || c.Feishu.AppSecret == "" {
			return fmt.Errorf("feishu 已启用但 app_id 或 app_secret 为空")
		}
	}
	if c.AI.Enabled {
		if c.AI.BaseURL == "" || c.AI.APIKey == "" || c.AI.Model == "" {
			return fmt.Errorf("ai 已启用但 base_url/api_key/model 为空")
		}
		if c.AI.TimeoutSeconds <= 0 {
			c.AI.TimeoutSeconds = 15
		}
	}
	return nil
}
