package config

import (
	"ai_scheduler/pkg"
	"fmt"
	"time"

	"github.com/spf13/viper"
)

// Config 应用配置
type Config struct {
	Server           ServerConfig     `mapstructure:"server"`
	Ollama           OllamaConfig     `mapstructure:"ollama"`
	Vllm             VllmConfig       `mapstructure:"vllm"`
	Coze             CozeConfig       `mapstructure:"coze"`
	LSXD             LSXDConfig       `mapstructure:"lsxd"`
	Sys              SysConfig        `mapstructure:"sys"`
	Tools            ToolsConfig      `mapstructure:"tools"`
	EinoTools        EinoToolsConfig  `mapstructure:"eino_tools"`
	Logging          LoggingConfig    `mapstructure:"logging"`
	Redis            Redis            `mapstructure:"redis"`
	DB               DB               `mapstructure:"db"`
	Mongo            Mongo            `mapstructure:"mongo"`
	Oss              Oss              `mapstructure:"oss"`
	DefaultPrompt    SysPrompt        `mapstructure:"default_prompt"`
	PermissionConfig PermissionConfig `mapstructure:"permissionConfig"`
	KnowledgeConfig  KnowledgeConfig  `mapstructure:"knowledge_config"`
	LLM              LLM              `mapstructure:"llm"`
	Dingtalk         DingtalkConfig   `mapstructure:"dingtalk"`
	Qywx             QywxConfig       `mapstructure:"qywx"`
}

type ZLTX struct {
	ReqUrl string `mapstructure:"req_url"`
}

type SysPrompt struct {
	ImgRecognize DefaultPrompt `mapstructure:"img_recognize"`
}

type DefaultPrompt struct {
	SystemPrompt string `mapstructure:"system_prompt"`
	UserPrompt   string `mapstructure:"user_prompt"`
}

type LLM struct {
	Providers    map[string]LLMProviderConfig   `mapstructure:"providers"`
	Capabilities map[string]LLMCapabilityConfig `mapstructure:"capabilities"`
}
type LLMProviderConfig struct {
	Endpoint string     `mapstructure:"endpoint"`
	Timeout  string     `mapstructure:"timeout"`
	Models   []LLMModle `mapstructure:"models"`
}
type LLMModle struct {
	ID         string   `mapstructure:"id"`
	Name       string   `mapstructure:"name"`
	Streaming  bool     `mapstructure:"streaming"`
	Modalities []string `mapstructure:"modalities"`
	MaxTokens  int      `mapstructure:"max_tokens"`
}
type LLMParameters struct {
	Temperature float64 `mapstructure:"temperature"`
	MaxTokens   int     `mapstructure:"max_tokens"`
	Stream      bool    `mapstructure:"stream"`
}
type LLMCapabilityConfig struct {
	Provider   string        `mapstructure:"provider"`
	Model      string        `mapstructure:"model"`
	Parameters LLMParameters `mapstructure:"parameters"`
}

// DingtalkConfig 钉钉配置
type DingtalkConfig struct {
	ApiKey      string           `mapstructure:"api_key"`
	ApiSecret   string           `mapstructure:"api_secret"`
	TableDemand AITableConfig    `mapstructure:"table_demand"`
	BotGroupID  map[string]int   `mapstructure:"bot_group_id"` // 机器人群组
	Card        CardConfig       `mapstructure:"card"`         // 互动卡片
	SceneGroup  SceneGroupConfig `mapstructure:"scene_group"`  // 场景群
}

// QywxConfig 企业微信配置
type QywxConfig struct {
	CorpId          string         `mapstructure:"corp_id"`
	DefaultConfigId int32          `mapstructure:"default_config_id"`
	AppSecret       string         `mapstructure:"app_secret"`
	InitAccount     string         `mapstructure:"init_account"`
	Token           string         `mapstructure:"token"`
	AES_KEY         string         `mapstructure:"aes_key"`
	ChatIdLen       int            `mapstructure:"chat_id_len"`
	BotGroupID      map[string]int `mapstructure:"bot_group_id"` // 应用群
}

// TableDemandConfig 需求表配置
type AITableConfig struct {
	Url           string `mapstructure:"url"`
	BaseId        string `mapstructure:"base_id"`
	SheetIdOrName string `mapstructure:"sheet_id_or_name"`
}

// CardConfig 互动卡片配置
type CardConfig struct {
	// 卡片回调路由key
	CallbackRouteKey string `mapstructure:"callback_route_key"`
	// 卡片调试工具 [show：展示 hide：隐藏]
	DebugToolEntryShow string `mapstructure:"debug_tool_entry_show"`
	// 卡片模板
	Template CardTemplateConfig `mapstructure:"template"`
}

// CardTemplateConfig 卡片模板配置
type CardTemplateConfig struct {
	// 基础消息卡片(title + content)
	BaseMsg string `mapstructure:"base_msg"`
	// 内容收集卡片（title + textarea + button）
	ContentCollect string `mapstructure:"content_collect"`
	// 创建群聊申请（title + content + button）
	CreateGroupApprove string `mapstructure:"create_group_approve"`
}

// SceneGroupConfig 场景群配置
type SceneGroupConfig struct {
	// 问题处理群模板ID
	GroupTemplateIDIssueHandling string `mapstructure:"group_template_id_issue_handling"`
	// 问题处理群模板机器人ID
	GroupTemplateRobotIDIssueHandling string `mapstructure:"group_template_robot_id_issue_handling"`
}

// SysConfig 系统配置
type SysConfig struct {
	SessionLen        int `mapstructure:"session_len"`
	ChannelPoolLen    int `mapstructure:"channel_pool_len"`
	ChannelPoolSize   int `mapstructure:"channel_pool_size"`
	LlmPoolLen        int `mapstructure:"llm_pool_len"`
	HeartbeatInterval int `mapstructure:"heartbeat_interval"`
}

// ServerConfig 服务器配置
type ServerConfig struct {
	Port int    `mapstructure:"port"`
	Host string `mapstructure:"host"`
}

// OllamaConfig Ollama配置
type OllamaConfig struct {
	BaseURL       string        `mapstructure:"base_url"`
	Model         string        `mapstructure:"model"`
	GenerateModel string        `mapstructure:"generate_model"`
	MappingModel  string        `mapstructure:"mapping_model"`
	VlModel       string        `mapstructure:"vl_model"`
	Timeout       time.Duration `mapstructure:"timeout"`
}

type VllmConfig struct {
	VLModel   VllmModel `mapstructure:"vl_model"`
	TextModel VllmModel `mapstructure:"text_model"`
}

type VllmModel struct {
	BaseURL string        `mapstructure:"base_url"`
	Model   string        `mapstructure:"model"`
	Timeout time.Duration `mapstructure:"timeout"`
	Level   string        `mapstructure:"level"`
}

// CozeConfig Coze配置
type CozeConfig struct {
	BaseURL   string `mapstructure:"base_url"`
	ApiKey    string `mapstructure:"api_key"`
	ApiSecret string `mapstructure:"api_secret"`
}

// LSXDConfig 统一登录配置
type LSXDConfig struct {
	LoginURL      string `mapstructure:"login_url"`
	Phone         string `mapstructure:"phone"`
	Password      string `mapstructure:"password"`
	Code          string `mapstructure:"code"`
	CheckTokenURL string `mapstructure:"check_token_url"`
}

type Redis struct {
	Host        string `mapstructure:"host"`
	Type        string `mapstructure:"type"`
	Pass        string `mapstructure:"pass"`
	Key         string `mapstructure:"key"`
	Tls         int32  `mapstructure:"tls"`
	Db          int32  `mapstructure:"db"`
	MaxIdle     int32  `mapstructure:"maxIdle"`
	PoolSize    int32  `mapstructure:"poolSize"`
	MaxIdleTime int32  `mapstructure:"maxIdleTime"`
}

type DB struct {
	Driver string `mapstructure:"driver"`

	Source      string `mapstructure:"source"`
	MaxIdle     int32  `mapstructure:"maxIdle"`
	MaxOpen     int32  `mapstructure:"maxOpen"`
	MaxLifetime int32  `mapstructure:"maxLifetime"`
	IsDebug     bool   `mapstructure:"isDebug"`
}

type Mongo struct {
	Source          string `mapstructure:"source"`
	DataBase        string `mapstructure:"dataBase"`
	MaxPoolSize     uint64 `mapstructure:"maxPoolSize"`
	MinPoolSize     uint64 `mapstructure:"minPoolSize"`
	MaxConnIdleTime int32  `mapstructure:"maxConnIdleTime"`
	ConnectTimeout  int32  `mapstructure:"connectTimeout"`
	SocketTimeout   int32  `mapstructure:"socketTimeout"`
}

// Oss 阿里云OSS配置
type Oss struct {
	AccessKey string `mapstructure:"access_key"`
	SecretKey string `mapstructure:"secret_key"`
	Bucket    string `mapstructure:"bucket"`
	Domain    string `mapstructure:"domain"`
	Endpoint  string `mapstructure:"endpoint"`
}

// ToolsConfig 工具配置
type ToolsConfig struct {
	Weather            ToolConfig `mapstructure:"weather"`
	Calculator         ToolConfig `mapstructure:"calculator"`
	ZltxOrderDetail    ToolConfig `mapstructure:"zltxOrderDetail"`
	ZltxOrderDirectLog ToolConfig `mapstructure:"zltxOrderDirectLog"`
	Knowledge          ToolConfig `mapstructure:"knowledge"`
	//通过ID获取我们的商品信息
	ZltxProduct ToolConfig `mapstructure:"zltxProduct"`
	//通过账号获取订单统计信息
	ZltxOrderStatistics ToolConfig `mapstructure:"zltxOrderStatistics"`
	DingTalkBot         ToolConfig `mapstructure:"dingTalkBot"`
	// 上游订单售后
	ZltxOrderAfterSaleSupplier ToolConfig `mapstructure:"zltxOrderAfterSaleSupplier"`
	// 下游订单售后
	ZltxOrderAfterSaleReseller ToolConfig `mapstructure:"zltxOrderAfterSaleReseller"`
	// 下游批充订单售后
	ZltxOrderAfterSaleResellerBatch ToolConfig `mapstructure:"zltxOrderAfterSaleResellerBatch"`
	// Coze 快递查询工具
	CozeExpress ToolConfig `mapstructure:"cozeExpress"`
	// Coze 公司查询工具
	CozeCompany                                          ToolConfig `mapstructure:"cozeCompany"`
	ZltxResellerAuthProductToManagerAndDefaultLossReason ToolConfig `mapstructure:"zltxResellerAuthProductToManagerAndDefaultLossReason"`
}

// ToolConfig 单个工具配置
type ToolConfig struct {
	Enabled   bool   `mapstructure:"enabled"`
	BaseURL   string `mapstructure:"base_url"`
	APIKey    string `mapstructure:"api_key"`
	APISecret string `mapstructure:"api_secret"`
	//附加地址
	AddURL string `mapstructure:"add_url"`
}

// EinoToolsConfig eino tool 配置
type EinoToolsConfig struct {
	// 货易通商品上传
	HytProductUpload ToolConfig `mapstructure:"hytProductUpload"`
	// 货易通供应商查询
	HytSupplierSearch ToolConfig `mapstructure:"hytSupplierSearch"`
	// 货易通仓库查询
	HytWarehouseSearch ToolConfig `mapstructure:"hytWarehouseSearch"`
	// 货易通商品添加
	HytGoodsAdd ToolConfig `mapstructure:"hytGoodsAdd"`
	// 货易通商品图片添加
	HytGoodsMediaAdd ToolConfig `mapstructure:"hytGoodsMediaAdd"`
	// 货易通商品分类添加
	HytGoodsCategoryAdd ToolConfig `mapstructure:"hytGoodsCategoryAdd"`
	// 货易通商品分类查询
	HytGoodsCategorySearch ToolConfig `mapstructure:"hytGoodsCategorySearch"`
	// 货易通商品品牌查询
	HytGoodsBrandSearch ToolConfig `mapstructure:"hytGoodsBrandSearch"`
	// 负利润分析列表、 详情
	DaOursProductLoss ToolConfig `mapstructure:"daOursProductLoss"`
	// 利润同比排行榜
	DaProfitRanking ToolConfig `mapstructure:"daProfitRanking"`
	// 销售同比分析列表
	DaOfficialProduct ToolConfig `mapstructure:"daOfficialProduct"`
	// 销售同比下滑详情
	DaOfficialProductDecline ToolConfig `mapstructure:"daOfficialProductDecline"`
	// 我们的商品统计
	RechargeStatisticsOursProduct ToolConfig `mapstructure:"rechargeStatisticsOursProduct"`
	// Excel 转图片
	Excel2Pic ToolConfig `mapstructure:"excel2Pic"`
}

// LoggingConfig 日志配置
type LoggingConfig struct {
	Level  string `mapstructure:"level"`
	Format string `mapstructure:"format"`
}

// PermissionConfig 权限校验配置
type PermissionConfig struct {
	// 获取权限的地址
	PermissionURL string `mapstructure:"permission_url"`
}

// KnowledgeConfig 知识库配置
type KnowledgeConfig struct {
	// 知识库地址
	BaseURL string `mapstructure:"base_url"`
	// 默认租户ID
	TenantID string `mapstructure:"tenant_id"`
	// 模式
	Mode string `mapstructure:"mode"`
	// 是否思考
	Think bool `mapstructure:"think"`
	// 是否仅RAG
	OnlyRAG bool `mapstructure:"only_rag"`
}

// LoadConfig 加载配置
func LoadConfig(configPath string) (*Config, error) {
	viper.SetConfigFile(configPath)
	viper.SetConfigType("yaml")

	// 设置默认值
	//viper.SetDefault("server.port", "8080")
	//viper.SetDefault("server.host", "0.0.0.0")
	//viper.SetDefault("ollama.base_url", "http://localhost:11434")
	//viper.SetDefault("ollama.model", "llama2")
	//viper.SetDefault("ollama.timeout", "30s")
	//viper.SetDefault("logging.level", "info")
	//viper.SetDefault("logging.format", "json")

	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		return nil, fmt.Errorf("failed to read config file: %w", err)
	}

	// 解析配置
	var bc Config
	if err := viper.Unmarshal(&bc); err != nil {
		return nil, fmt.Errorf("failed to unmarshal config: %w", err)
	}

	return &bc, nil
}

func LoadConfigWithTest() (*Config, error) {
	var bc Config
	modularDir, err := pkg.GetModuleDir()
	if err != nil {
		return nil, err
	}
	viper.SetConfigFile(modularDir + "/config/config_test.yaml")
	viper.SetConfigType("yaml")
	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		return nil, fmt.Errorf("failed to read config file: %w", err)
	}
	// 解析配置

	if err := viper.Unmarshal(&bc); err != nil {
		return nil, fmt.Errorf("failed to unmarshal config: %w", err)
	}

	return &bc, nil

}

func LoadConfigWithEnv() (*Config, error) {
	var bc Config
	modularDir, err := pkg.GetModuleDir()
	if err != nil {
		return nil, err
	}
	viper.SetConfigFile(modularDir + "/config/config.yaml")
	viper.SetConfigType("yaml")
	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		return nil, fmt.Errorf("failed to read config file: %w", err)
	}
	// 解析配置

	if err := viper.Unmarshal(&bc); err != nil {
		return nil, fmt.Errorf("failed to unmarshal config: %w", err)
	}

	return &bc, nil

}
